简体   繁体   English

我如何将 json 对象作为 json 数组

[英]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.我有一个 json 作为我的 api 调用的一部分返回,如下所示。

{
  '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.但它正在剥离外部 JSON 键。

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.旁注:我在过去的 2-3 天内看到很多类似的问题,人们想要带有键的“JSON 数组”,并且他们还小心地在数组末尾放置了一个“空”逗号。 Are you guys coming from some course?你们是从某个课程来的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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