如何从另一个嵌套对象构建一个新对象[重复]

问题描述 投票:-3回答:3

我有一个大型的Object,结构如下。

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

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

我试图获取名称,类型等字段,我想构建一个新的对象。

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

像这样,但有什么方法可以通过迭代实现这一点?

谢谢。

javascript arrays json object
3个回答
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
投票

你可以把想要的财产。

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; }

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; }
© www.soinside.com 2019 - 2024. All rights reserved.