karan
karan

Reputation: 65

Reading only the first value in JavaScript

I am trying to add the below body to JSON. But I only see one value is being added.

json = { "Myname":"Nate",  }

Adding the below code:

Body = Myproperty: [{
  "vehicle": "car",
  "color": "Red"
}, {
  "name": "van",
  "color": "white"
}, {
  "name": "Truck",
  "color": "Blue"
}]

Here is the code I am using:

for (var i = 0; i < Myproperty.length; i++) {
  json.mycarname = Body.Myproperty[i].name;
  json.mycolor = Body.Myproperty[i].color;
}

The end result should look like this:

{
  "Myname": "Nate",
  mycarname: "car",
  "mycolor": "Red"
},
{
  "Myname": "Nate",
  mycarname: "van",
  "mycolor": "white"
},
{
  "Myname": "Nate",
  mycarname: "Truck",
  "mycolor": "Blue"
}

Upvotes: 0

Views: 133

Answers (1)

Oram
Oram

Reputation: 1673

I guess you want to do something like this:

var myName = "Nate";

var Body = [{
    "name": "car",
    "color": "Red"
  },
  {
    "name": "van",
    "color": "white"
  },
  {
    "name": "Truck",
    "color": "Blue"
  }
]

var json = [];
for (var i = 0; i < Body.length; i++) {
  json.push({
    "Myname": myName,
    "mycarname": Body[i].name,
    "mycolor": Body[i].color
  });
}

console.log(json)

The idea is to loop over the entries you want to add and push them into the json array.

Upvotes: 1

Related Questions