简体   繁体   English

如何在javascript中将json对象转换为json数组

[英]How to covert json object to json array in javascript

The JSON object I have我拥有的 JSON 对象

{Yana: 1, Pirelli: 2, Good Year: 1}

Expected results预期成绩

series: [
         {name: 'Yana', data: [1]},
         {name: 'Pirelli', data: [5]},
         {name: 'Good year', data: [5]}
        ]

Object.entries will help here Object.entries 在这里会有所帮助

 var input = {"Yana": 1, "Pirelli": 2, "Good Year": 1}; var output = Object.entries(input).map(([name, v]) => ({name, data:[v]})); console.log (output);

How about this:这个怎么样:

const object = {"Yana": 1, "Pirelli": 2, "Good Year": 1};

Object.keys(object).map(key => {
    return {name: key, data: [object[key]]};
})

Object.keys gets an array of the key names from object which can be iterated over using map . Object.keysobject获取一个键名数组,可以使用map对其进行迭代。 Using this it's then simple to construct the output array in your desired format.使用它可以很容易地以您想要的格式构造输出数组。

You can use a forEach() in Object.keys() for data object:您可以在Object.keys()使用forEach() Object.keys()作为data对象:

 var data = {"Yana":1,"Pirelli":2,"Good Year":1}; var res = []; Object.keys(data).forEach(key => res.push({name: key, data:[data[key]]})); console.log(res);

The object you provided is not a valid JSON object.您提供的对象不是有效的 JSON 对象。 In JSON format your object would be:在 JSON 格式中,您的对象将是:

{"Yana": 1, "Pirelli": 2, "Good Year": 1}

Assuming that you have that in a string, first thing you need to do is to parse it as JS object:假设你在一个字符串中有它,你需要做的第一件事就是将它解析为 JS 对象:

const jsonData = '{"Yana": 1, "Pirelli": 2, "Good Year": 1}'
const object = JSON.parse(jsonData);

// Now get all the keys from the object:
const brands = Object.keys(object);

// Finally, create a new object with the desired properties:
const result = brands.map(brand => {
  return {
    name: brand,
    data: object[brand]
  };
})

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

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