这个问题在这里已有答案:
我有一个大型的Object,结构如下。
[
{
"Name": "xxx",
"Company": "Google",
"Type": "Search",
},
{
"Name": "yyy",
"Company": "MS",
"Type": "Search",
}
]
我试图获取名称,类型等字段,我想构建一个新的对象。
var newArray = [];
newArray.push = [ {
object[0].Name,
object[0].Type } ]
像这样,但有什么方法可以通过迭代实现这一点?
谢谢。
您可以使用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)
你可以把想要的财产。
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; }
使用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; }