javascript中是否有一種方法可以從作為物件陣列一部分的物件中遍歷特定鍵的每個值,然后使用不同的鍵為每個值創建一個新項?請允許我用代碼解釋我想在這里完成什么。
這就是我所擁有的:
const x = [{
name: 'name1',
value: ['value1', 'value2', 'value3']
}, {
name: 'name2',
value: ['value4', 'value5', 'value6']
}]
這應該是新的結果:
const y = [{
'name1': 'value1',
'name2': 'value4',
}, {
'name1': 'value2',
'name2': 'value5',
}, {
'name1': 'value3',
'name2': 'value6',
}]
任何幫助將不勝感激!
這是我到目前為止所嘗試的。(它有效,但我很確定有一種更簡單的方法)。
const y = [];
const z = [];
const xLength = x.length
for (let i = 0; i < xLength; i ) {
x[i].value.forEach((item, index) => {
z[index] = z[index] || [];
z[index].push(x[i].name, item);
});
}
z.forEach((items, index) => {
const obj = {};
items.forEach((item, k) => {
if (k % 2) {
obj[items[k - 1]] = item;
} else {
obj[item] = null;
}
});
y.push(obj);
});
uj5u.com熱心網友回復:
我相信這應該有效:
//start with array to store the answer
let y = []
//Next iterate threw each object in your 'x' array passing in to the callback xObj which is each object in your x array
x.forEach((xObj)=> {
//store the name value just to make it easier to read
let name = xObj.name
//iterate through the values in each xObj, getting the 'value' and the index
xObj.value.forEach((value, index)=>{
//check if the y array has anything at the same index, if not create a blank object
if(!y[index]) y[index]= {}
//put in that object a key:value with the 'name' and 'value'
y[index][name] = value
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/417907.html
標籤:
上一篇:Python輸入陣列一行
