0

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?

1
  • 1
    Array.prototype.reduce() is your best friend. Commented Jan 3, 2017 at 19:42

4 Answers 4

2

Did i understand you?

var element = ExampleArray[0];

element.subject = ExampleArray.map(item=>item.subject);
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.