我有以下形式的对象数组
Buttons
我想将其转换为
Container
我如何实现这一目标?
答案 0 :(得分:0)
使用foreach循环
var data = [{
"name": "Lenovo Thinkpad 41A4298",
"website": "google"
},
{
"name": "Lenovo Thinkpad 41A2222",
"website": "google"
},
{
"name": "Lenovo Thinkpad 41Awww33",
"website": "yahoo"
}
];
var Result = [];
var Key = Object.keys(data[0]); // get keys in a variable
// use index insted of specific key
data.forEach(function(item) {
Result.push({ Brand: item[Key[0]], Link: item[Key[1]] });
});
console.log(Result);

答案 1 :(得分:0)
您可以使用map
循环访问数组。不使用密钥,您可以使用Object.values
将对象转换为数组。在Brand上分配数组的第一个元素,在Link上分配第二个元素以形成新对象。
var data = [{
"name": "Lenovo Thinkpad 41A4298",
"website": "google"
},
{
"name": "Lenovo Thinkpad 41A2222",
"website": "google"
},
{
"name": "Lenovo Thinkpad 41Awww33",
"website": "yahoo"
}
];
var result = data.map(o => {
let v = Object.values(o);
return {"Brand": v[0],"Link": v[1]};
});
console.log(result);

答案 2 :(得分:0)
Array.map可能是你的朋友 - 返回一个新数组,每个元素都是你传递给.map函数的函数的返回结果。
Mozilla Developer Network链接到Array.map参考here
在这个例子中
let data = [
{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"}
];
let newData = data.map((originalObject)=>{
return {
"Brand":originalObject.name,
"Link":originalObject.website
}
})
console.log(newData)

如果你想变得更加漂亮 - 你可以使用对象破坏here - about half way down来使代码更整洁
let data = [
{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"}
];
let newData = data.map(( {name,website} )=>{
return {
"Brand":name,
"Link":website
}
})
console.log(newData)

答案 3 :(得分:-1)
像这样:
var data = [{ "name": "Lenovo Thinkpad 41A4298", "website": "google" },
{ "name": "Lenovo Thinkpad 41A2222", "website": "google" },
{ "name": "Lenovo Thinkpad 41Awww33", "website": "yahoo" }];
const newData = data.map(obj => ({ Brand: obj.name, Link: obj.website }));
console.log(newData);

为了使其更加动态,您可以创建一些映射:
var data = [{ "name": "Lenovo Thinkpad 41A4298", "website": "google" },
{ "name": "Lenovo Thinkpad 41A2222", "website": "google" },
{ "name": "Lenovo Thinkpad 41Awww33", "website": "yahoo" },
{ "rate": "25", "review": "Well done" }];
const mappings = {
name: 'Brand',
website: 'Link',
review: 'Review',
rate: 'Rate'
}
const newData = data.map(obj => {
const newObj = {};
const keys = Object.keys(mappings);
keys.forEach(key => {
if (obj[key]) {
const newName = mappings[key];
newObj[newName] = obj[key];
}
});
return newObj;
});
console.log(newData);

然后你可以改变"映射"基于源数据或您想用它做的任何事情。