我目前有以下数组:
var ExampleArray=[]; //example array Name
ExampleArray.push ({
"No": 1,
"Name": "BB",
"subject": "NS"
},{
"No": 1,
"Name": "BB",
"subject": "PS"
},{
"No": 1,
"Name": "BB",
"subject": "KS"
}
我想将该数组转换为以下数组(使用嵌套对象)。
var array = {
"No": 1,
"Name": "BB",
"subject":
{
["NS","SS","KS"]
}
}
我该怎么做?
答案 0 :(得分:2)
使用Object#assign
创建一个新对象,并将数组中的一个对象与包含您使用Array#map
创建的主题数组的新对象合并。
注意:使用Object#assign
创建新对象而不会改变原始对象。
var ExampleArray = [{ "No": 1, "Name": "BB", "subject": "NS" },{ "No": 1, "Name": "BB", "subject": "PS" },{ "No": 1, "Name": "BB", "subject": "KS" }];
var object = Object.assign({}, ExampleArray[0], {
subject: ExampleArray.map(function(o) {
return o.subject;
})
});
console.log(object);

答案 1 :(得分:2)
我明白了吗?
var element = ExampleArray[0];
element.subject = ExampleArray.map(item=>item.subject);
答案 2 :(得分:1)
在这些情况下,只有你可以这样做;
var data = [{ "No": 1,
"Name": "BB",
"subject": "NS"},
{ "No": 1,
"Name": "BB",
"subject": "PS"},
{ "No": 1,
"Name": "BB",
"subject": "KS"
}
],
result = data.reduce((p,c) => Object.assign(c,(p.subject = p.subject.concat(c.subject),p)), {subject:[]});
console.log(result);

答案 3 :(得分:0)
使用for循环
var ExampleArray = [];
ExampleArray.push ({"No": 1,"Name": "BB","subject": "NS"},{"No": 1,"Name": "BB","subject": "PS"},{"No": 1,"Name": "BB","subject":"KS"});
var array_subject = [];
for(var i in ExampleArray)
array_subject.push(ExampleArray[i].subject);
ExampleArray[0].subject = array_subject;
var result = ExampleArray[0];
console.log(result);