二层嵌套的对象,如何转换成一级对象?

[
{"fields":{"itemname":"aaa","qty":100},"billno":"a001"},
{"fields":{"itemname":"bbb","qty":300},"billno":"a002"},
{"fields":{"itemname":"ccc","qty":200},"billno":"a004"},
{"fields":{"itemname":"eee","qty":800},"billno":"a006"},
……
]

想转换为下面这个
[
{"itemname":"aaa","qty":100,"billno":"a001"},
{"itemname":"bbb","qty":300,"billno":"a002"},
{"itemname":"ccc","qty":200,"billno":"a004"},
{"itemname":"eee","qty":800,"billno":"a006"},
……
]

小白求各位大神指导!

阅读 3.2k
6 个回答
const arr = [
{"fields":{"itemname":"aaa","qty":100},"billno":"a001"},
{"fields":{"itemname":"bbb","qty":300},"billno":"a002"},
{"fields":{"itemname":"ccc","qty":200},"billno":"a004"},
{"fields":{"itemname":"eee","qty":800},"billno":"a006"},
]
const newArr = arr.map(item => {return {...item.fields,billno:item.billno}})
 console.log(newArr)

image.png

image.png

image.png

  const sourceData = [
    { "fields": { "itemname": "aaa", "qty": 100 }, "billno": "a001" },
    { "fields": { "itemname": "bbb", "qty": 300 }, "billno": "a002" },
    { "fields": { "itemname": "ccc", "qty": 200 }, "billno": "a004" },
    { "fields": { "itemname": "eee", "qty": 800 }, "billno": "a006" },
  ];

  const targetData = sourceData.map(item => ({
    itemname: item.fields.itemname,
    qty: item.fields.qty,
    billno: item.billno,
  }));

  console.log(targetData);
let data = [
    { fields: { itemname: "aaa", qty: 100 }, billno: "a001" },
    { fields: { itemname: "bbb", qty: 300 }, billno: "a002" },
    { fields: { itemname: "ccc", qty: 200 }, billno: "a004" },
    { fields: { itemname: "eee", qty: 800 }, billno: "a006" },
];
let arr = data.map(({ fields, ...arg }) => ({ ...arg, ...fields }));
console.log(arr);
const arr = [
    {"fields":{"itemname":"aaa","qty":100},"billno":"a001"},
    {"fields":{"itemname":"bbb","qty":300},"billno":"a002"},
    {"fields":{"itemname":"ccc","qty":200},"billno":"a004"},
    {"fields":{"itemname":"eee","qty":800},"billno":"a006"},
]
const brr = arr.map(({fields,billno}) => ({
    ...fields,
    billno
}))

image.png

const arr = [

    {"fields": {"itemname": "aaa", "qty": 100}, "billno": "a001"},
    {"fields": {"itemname": "bbb", "qty": 300}, "billno": "a002"},
    {"fields": {"itemname": "ccc", "qty": 200}, "billno": "a004"},
    {"fields": {"itemname": "eee", "qty": 800}, "billno": "a006"},
]

const newArr=arr.map(item => {
    const fields=item.fields
    delete item.fields

    return {
        ...item,
        ...fields,

    }
})
console.log(newArr)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题