我必須安排一個訂單串列,然后在準備好資料之后,需要將這個物件串列插入另一個物件中。
我創建了一個簡化的代碼以便更好地理解:
const orderList = [];
orderList.push({
order1: { desc: "smt1" }
})
orderList.push({
order2: { desc: "smt2" }
})
const result = {
anotherVar1: 1,
anotherVar2: 2,
...orderList
}
console.log("result", result)
輸出
{
'0': { order1: { desc: 'smt1' } },
'1': { order2: { desc: 'smt2' } },
anotherVar1: 1,
anotherVar2: 2,
}
期望的輸出:
{
order1: { desc: 'smt1' },
order2: { desc: 'smt2' },
anotherVar1: 1,
anotherVar2: 2,
}
如何達到預期的輸出?
uj5u.com熱心網友回復:
作為一個更好的方法,將該陣列作為一個物件,這樣您就可以避免重復和額外的回圈
和你的方法一樣,你可以按照這個代碼來制作你想要的輸出
const orderList = [];
orderList.push({
order1: { desc: "smt1" }
})
orderList.push({
order2: { desc: "smt2" }
})
const result = {
anotherVar1: 1,
anotherVar2: 2,
}
orderList.map(d => {
for(key in d) {
result[key] = d[key]
}
})
console.log("result", result)
uj5u.com熱心網友回復:
你想orderList成為一個物件,而不是一個陣列。然后push,您希望在物件上設定鍵/值,而不是使用。
const orderList = {};
orderList.order1 = { desc: "smt1" };
orderList.order2 = { desc: "smt2" };
const result = {
anotherVar1: 1,
anotherVar2: 2,
...orderList
}
console.log('result', result);
uj5u.com熱心網友回復:
正如@Rocket Hazmat在他的回答中提到的,使用一個物件而不是一個陣列
要回答原始問題,您需要先將物件陣列轉換為物件,然后才能“合并”它們
const orderList = [];
orderList.push({ order1: { desc: "smt1" } });
orderList.push({ order2: { desc: "smt2" } });
const result = {
anotherVar1: 1,
anotherVar2: 2,
...Object.assign({}, ...orderList)
};
console.log('result', result);
如何將物件陣列轉換為具有鍵值對的物件
uj5u.com熱心網友回復:
您可以在不更改代碼的情況下嘗試這一行 -
orderList.map((item) => (result = { ...item, ...result }));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/339626.html
標籤:javascript 循环 索引
下一篇:如何在R編程中將回圈擴展n次?
