[英]how to create a nested array of objects for below array using javascript
I currently have the following array: 我目前有以下数组:
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"
}
I want to turn that array into the following array (with a nested object). 我想将该数组转换为以下数组(带有嵌套对象)。
var array = {
"No": 1,
"Name": "BB",
"subject":
{
["NS","SS","KS"]
}
}
How do I do this? 我该怎么做呢?
Create a new object by using Object#assign
, and merge one of the objects in the array with a new object that contains the subjects array you create with Array#map
. 通过使用
Object#assign
创建一个新对象,并将数组中的一个对象与一个新对象合并,该对象包含使用Array#map
创建的subjects数组。
Note: Using Object#assign
creates a new object without mutating the original objects. 注意:使用
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);
Did i understand you? 我了解你吗?
var element = ExampleArray[0];
element.subject = ExampleArray.map(item=>item.subject);
Well under these conditions only you may do as follows; 在这些条件下,您只能执行以下操作;
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);
Using a for loop 使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.