0

Object is:

 people[resident1:[
     "name" : "valueForName",
     "address" : "valueForAddress",
     "city"  : "valueForCity"
],
resident2:[
     "name" : "valueForName",
     "address" : "valueForAddress",
     "city"  : "valueForCity"
]]

People has more than one residents, I want a JSON that has following structure:

"residents" :{
    "valueForName1":"valueForCity1",
    "valueForName2":"valueForCity2"
}

Can anyone help? I am new to javascript. Thank you!

7
  • residents is wrong, should be {} not [].... why are you not using an Array holding multiple addresses? Commented Apr 13, 2017 at 23:47
  • Sorry, I was not clear, 'residents' is and object inside the object 'people'. and I want to create a JSON that looks like shown in the second code snippet. Commented Apr 13, 2017 at 23:57
  • @Amruta, please provide a correct example of your source object Commented Apr 14, 2017 at 0:44
  • @Dancrumb I have updated the example. I have a people object inside which there is a list of 'resident' objects, 'resident' object has properties 'name' and 'city'. I need to display a JSON in the format: shown in snippet 2. Commented Apr 14, 2017 at 0:55
  • Your object is not a valid JSON object. Commented Apr 14, 2017 at 1:41

2 Answers 2

2

You should have an array that contains objects:

{
  "residents": [{
    "name": "valueForName1",
    "address": "valueForAddress1",
    "city": "valueForCity1"
  }, {
    "name": "valueForName2",
    "address": "valueForAddress2",
    "city": "valueForCity2"
  }]
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could do something like this,

var result = {};
var residents = [];
var resident1 = {};
var resident2 = {};

resident1.name = "Joe";
resident1.address = "street1";
resident1.city = "Boston";

resident2.name = "Smith";
resident2.address = "street2";
resident2.city = "New York";

residents.push(resident1);
residents.push(resident2);

result.residents = residents;

console.log(JSON.stringify(result));

It prints below

{
  "residents": [
    {
      "name": "Joe",
      "address": "street1",
      "city": "Boston"
    },
    {
      "name": "Smith",
      "address": "street2",
      "city": "New York"
    }
  ]
}

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.