Javascript 转换对象结构数组

Javascript transform array of object structure

我正在尝试将对象结构数组转换为如下所示:

[
  {
    id: 1,
    val: "bool",
    name: "somename",
    entities: [
      {
        id: 1,
        name: "varchar",
        type: "string"
      }
    ]
  },
  {
    id: 2,
    val: "bool",
    name: "somename",
    entities: [
      {
        id: 1,
        name: "varchar",
        type: "string"
      }
    ]
  }
]

进入这个:

[
  {
    id: 1,
    val: "bool",
    name: "somename",
    entitiesName: "varchar",
    entitiesType: "string"
  },
  {
    id: 2,
    val: "bool",
    name: "somename",
    entitiesName: "varchar",
    entitiesType: "string"
  }
]

所以或多或少我想从 entities 中获取两个值,并将它们变成根对象中的 key/values。

我试过使用 Object.entries(data).map() 但我卡住了

使用Array.map()

  1. 创建两个新的键值对entitiesNameentitiesType
  2. 删除 entities

var data = [{
    id: 1,
    val: "bool",
    name: "somename",
    entities: [{
      id: 1,
      name: "varchar",
      type: "string"
    }]
  },
  {
    id: 2,
    val: "bool",
    name: "somename",
    entities: [{
      id: 1,
      name: "varchar",
      type: "string"
    }]
  }
];

data = data.map(
  (el) => {
      el.entitiesName = el.entities[0].name;
      el.entitiesType = el.entities[0].type;
      delete el.entities;
      return el;
  }
);

console.log(data);

您可以使用破坏来收集所有想要的属性并构建一个新对象。

var array = [{ id: 1, val: "bool", name: "somename", entities: [{ id: 1, name: "varchar", type: "string" }] }, { id: 2, val: "bool", name: "somename", entities: [{ id: 1, name: "varchar", type: "string" }] }],
    result = array.map(
        ({ id, val, name, entities: [{ name: entitiesName, type: entitiesType }] }) =>
        ({ id, val, name, entitiesName, entitiesType })
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

避免修改源数组。

var data = [  {    id: 1,    val: "bool",    name: "somename",    entities: [      {        id: 1,        name: "varchar",        type: "string"      }    ]  },  {    id: 2,    val: "bool",    name: "somename",    entities: [      {        id: 1,        name: "varchar",        type: "string"      }    ]  }];

var result = data.map((o) => {
  var obj = {...o, 'entitiesName': o.entities[0].name, 'entitiesType': o.entities[0].type };
  delete obj.entities;
  
  return obj;
});

console.log(data);
console.log(result);
.as-console-wrapper {
  max-height: 100% !important
}

您可以通过使用数组的 Array.map 函数和展开运算符来做到这一点

var data = [{
    id: 1,
    val: "bool",
    name: "somename",
    entities: [{
      id: 1,
      name: "varchar1",
      type: "string"
    }]
  },
  {
    id: 2,
    val: "bool",
    name: "somename",
    entities: [{
      id: 1,
      name: "varchar2",
      type: "string"
    }]
  }
];
var result = data.map(
  (el) => {
      const { entities, ...noentities } = el;
      return {...noentities, entitiesName :el.entities[0].name ,entitiesType:el.entities[0].type}
  }
);
console.log(result)