简体   繁体   English

将对象数组修改为 JavaScript 中的新对象数组

[英]Modify array of objects into new array of objects in JavaScript

I would like how to convert the object to array of objects in JavaScript.我想如何将 object 转换为 JavaScript 中的对象数组。 In object obj , fields should be modified to nested array of objects in JavaScript.在 object obj中,字段应修改为 JavaScript 中的嵌套对象数组。

 var obj = [{ id: 1, fields: { color: "white", brand: "xyz" } }] function objarray(obj) { return obj.map(e => ({ label: Object.keys(e.fields) })) } var result = objarray(obj); console.log(result);

Expected Output:预期 Output:

  [
    {
      label: "color",
      children: [{label:"white" }]
    },
    {
      label: "brand",
      children: [{label:"xyz" }]
    }
  ]

Obj.map isn't going to work as obj is an array with one element so it will only iterate one time. Obj.map 不起作用,因为 obj 是一个只有一个元素的数组,所以它只会迭代一次。

let newArray = []
for (var i in obj.fields)
{
    newArray.push({label: i, children:obj[[0].fields.i});
}

I doubt this will compile.我怀疑这会编译。 I suspect i is an object here and can't be used as a reference on obj[0].fields.我怀疑我在这里是 object,不能用作 obj[0].fields 的参考。

but You get the idea.但你明白了。

This should do the trick这应该可以解决问题

var obj = [{
  id: 1,
  fields: {
    color: "white",
    brand: "xyz"
  }
}]

const mapFields = (obj) => {
  return obj.map((o) => {
    return Object.keys(o.fields).map((f) => {
      var field = {
        label: f,
        children: [{label: o.fields[f]}]
      };
      return field;
    });
  })
}

console.log(mapFields(obj));

You can do this by making use of Object.entries() :您可以通过使用Object.entries()来做到这一点:

 var obj = [ { id: 1, fields: { color: "white", brand: "xyz" } }]; result = Object.entries(obj[0].fields).map(([k,v])=>({label:k, children:[{label:v}]})) console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM