The JSON object I have
{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
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
. 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:
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. In JSON format your object would be:
{"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:
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]
};
})
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.