我的物件目前看起來像這樣。我想將專案物件轉換為物件陣列。
const items = [
{
item_id: 1,
stock_on_hand: 400,
item: {
id: 1,
code: "ITEM 1",
},
},
{
item_id: 2,
stock_on_hand: 150,
item: {
id: 2,
code: "ITEM 2",
},
},
];
這個結果我想輸出:
const items = {
0: {
item_id: 1,
stock_on_hand: 400,
},
1: {
item_id: 2,
stock_on_hand: 150,
},
item: [
{
id: 1,
code: "ITEM 1",
},
{
id: 2,
code: "ITEM 2",
},
],
};
我嘗試過的:但專案物件仍在我要洗掉它們的物件內。
const arr = [];
for(const [key, value] of Object.entries(items)) {
arr.push(Object.assign({}, value.item));
}
const item = {...items, arr};
uj5u.com熱心網友回復:
只是從delete
_item
value
const arr = [];
for(const [key, value] of Object.entries(items)) {
arr.push(Object.assign({}, value.item));
delete value.item;
}
const item = {...items, arr};
uj5u.com熱心網友回復:
您可以使用 forEach 來完成它,如下所示:
const items = [
{
item_id: 1,
stock_on_hand: 400,
item: {
id: 1,
code: "ITEM 1",
},
},
{
item_id: 2,
stock_on_hand: 150,
item: {
id: 2,
code: "ITEM 2",
},
},
];
const obj = {};
items.forEach((el, idx) => {
const {item, ...otherProps} = el;
obj[idx] = otherProps;
obj.items ??= [];
obj.items.push(item);
})
console.log(obj);
uj5u.com熱心網友回復:
從技術上講,您不能完全按照您的意愿行事,因為您不能將整數用作物件的屬性(它們會被轉換為字串)。你可以接近:
const items = [
{
item_id: 1,
stock_on_hand: 400,
item: {
id: 1,
code: "ITEM 1",
},
},
{
item_id: 2,
stock_on_hand: 150,
item: {
id: 2,
code: "ITEM 2",
},
},
];
let result = items.reduce( (accum, current, index) => {
accum[index] = (({ item_id, stock_on_hand }) => ({item_id, stock_on_hand}))(current)
accum.item.push( current.item )
return accum
}, { item: [] })
console.log(result)
uj5u.com熱心網友回復:
實際上,您可以使用.reduce
和解構來轉換陣列
const items = [{item_id: 1,stock_on_hand: 400,item: {id: 1,code: "ITEM 1",},},{item_id: 2,stock_on_hand: 150,item: {id: 2,code: "ITEM 2",},},];
const result = items.reduce((acc, { item, ...rest }) => {
acc[rest.item_id] = rest;
acc.item.push(item);
return acc;
}, { item: [] });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }
uj5u.com熱心網友回復:
我們可以在沒有提及密鑰訪問的情況下獲得這種方式
const items = [
{ item_id: 1, stock_on_hand: 400, item: { id: 1, code: "ITEM 1"}},
{ item_id: 2, stock_on_hand: 150, item: { id: 2, code: "ITEM 2"}},
];
const func =(ar)=>{
const temp = []
ar.map((e, i)=> {
for(let [x, ind] of Object.entries(e)){
if(typeof ind == "object"){
temp.push(Object.assign({}, ar[ar.indexOf(e)][x]))
delete ar[ar.indexOf(e)][x]
}
}
})
const obj = {...ar , temp}
return obj
}
console.log(func(items))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/507572.html