简体   繁体   中英

How do i make json object as an json array

I've a json returned as part of my api call and it looks like below.

{
  'D1': {
    'name': 'Emp1',
    'Age':22
  },
  'D2': {
    'name': 'Emp2',
    'Age':43
  },
};

I want to convert this into an array. ie in the below format.

[
  'D1': {
    'name': 'Emp1',
    'Age':22
  },
  'D2': {
    'name': 'Emp2',
    'Age':43
  },
];

I'm trying to do it using the below code.

 let obj = { 'D1': { 'name': 'Emp1', 'Age':22 }, 'D2': { 'name': 'Emp2', 'Age':43 }, }; let wholeArray = Object.keys(obj).map(key => obj[key]); console.log(wholeArray);

But it is stripping off the outer JSON keys.

please let me know where am I going wrong and how to get the expected output.

You could separate the object into an array with only one key/value pair.

 let object = { D1: { name: 'Emp1', Age:22 }, D2: { name: 'Emp2', Age:43 } }, array = Object .entries(object) .map(pair => Object.fromEntries([pair])); console.log(array);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

This:

 [ 'D1': { 'name': 'Emp1', 'Age':22 }, 'D2': { 'name': 'Emp2', 'Age':43 }, ];

Simply does not exist. Arrays have no keys, objects do.

The most you could do is:

[
  {
    'D1': {
      'name': 'Emp1',
      'Age':22
    }
  },{
    'D2': {
      'name': 'Emp2',
      'Age':43
    }
  }
];

An array of objects with a single key.

One code variant for doing this:

 let obj = { 'D1': { 'name': 'Emp1', 'Age':22 }, 'D2': { 'name': 'Emp2', 'Age':43 }, }; //let wholeArray = Object.keys(obj).map(key => obj[key]); let wholeArray = Object.keys(obj).map(key => { let ret={}; ret[key]=obj[key]; return ret; }); console.log(wholeArray);

Side remark: I see a lot of similar question in the past 2-3 days, people want "JSON array" with keys, and they also carefully put an "empty" comma at the end of their arrays. Are you guys coming from some course?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM