[英]How to covert json object to json array in javascript
我擁有的 JSON 對象
{Yana: 1, Pirelli: 2, Good Year: 1}
預期成績
series: [
{name: 'Yana', data: [1]},
{name: 'Pirelli', data: [5]},
{name: 'Good year', data: [5]}
]
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);
這個怎么樣:
const object = {"Yana": 1, "Pirelli": 2, "Good Year": 1};
Object.keys(object).map(key => {
return {name: key, data: [object[key]]};
})
Object.keys
從object
獲取一個鍵名數組,可以使用map
對其進行迭代。 使用它可以很容易地以您想要的格式構造輸出數組。
您可以在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);
您提供的對象不是有效的 JSON 對象。 在 JSON 格式中,您的對象將是:
{"Yana": 1, "Pirelli": 2, "Good Year": 1}
假設你在一個字符串中有它,你需要做的第一件事就是將它解析為 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.