如何从另一个嵌套对象构建新对象

时间:2019-04-07 07:00:57

标签: javascript arrays json object

我有一个大型物体,其结构如下。

[
  {
    "Name": "xxx",
    "Company": "Google",
    "Type": "Search",

  },
  {
    "Name": "yyy",
    "Company": "MS",
    "Type": "Search",
  }
]

我正在尝试获取诸如名称,类型之类的字段,并且我想构建一个新的对象。

var newArray = [];
newArray.push = [ { 
object[0].Name,
object[0].Type } ]

就像这样,但是有什么办法可以通过使用迭代来实现?

谢谢。

3 个答案:

答案 0 :(得分:2)

您可以使用map并获取所需的键并使用所需的键和值构建一个新对象

let obj = [{"Name": "xxx","Company": "Google","Type": "Search",},{"Name": "yyy","Company": "MS","Type": "Search",}]

let op =obj.map(({Name,Type}) => ({Name,Type}))

console.log(op)

答案 1 :(得分:1)

您可以带走通缉的财产。

var source = [{ Name: "xxx", Company: "Google", Type: "Search" }, { Name: "yyy", Company: "MS", Type: "Search" }],
    target = source.map(({ Name, Type }) => ({ Name, Type }));
    
console.log(target);
.as-console-wrapper { max-height: 100% !important; top: 0; }

或者获取不需要的属性和其余的属性。

var source = [{ Name: "xxx", Company: "Google", Type: "Search" }, { Name: "yyy", Company: "MS", Type: "Search" }],
    target = source.map(({ Company, ...rest }) => rest);
    
console.log(target);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

使用map

const data = [{"Name": "xxx","Company": "Google","Type": "Search",},{"Name": "yyy","Company": "MS","Type": "Search"}];
const obj = data.map(({ Name, Type }) => ({ Name, Type }));
console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: auto; }