Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
1  
Array.prototype.reduce() is your best friend. – Redu Jan 3 at 19:42

Did i understand you?

var element = ExampleArray[0];

element.subject = ExampleArray.map(item=>item.subject);
share|improve this answer

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.

Note: Using Object#assign creates a new object without mutating the original objects.

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

share|improve this answer
    
Thanks Ori Drori – Naren Jan 3 at 19:45

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

share|improve this answer

Using a for loop

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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.