gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 13:02:17 25 4
gpt4 key购买 nike

我有json数据作为样本

[{"Food":"Orange T1","Total":3},
{"Food":"Blue T2","Total":1},
{"Food":"Green T3","Total":1},
{"Food":"White T4","Total":4}]

我想转换为数组对象

[['Orange T1', 3], ['Blue T2', 1], ['Green T3', 1],['White T4', 4]]

我如何做到这一点,我将使用 console.log() 来显示数据样本。

最佳答案

您可以映射每个对象的值。

var array = [{ Food: "Orange T1", Total: 3 }, { Food: "Blue T2", Total: 1 }, { Food: "Green T3", Total: 1 }, { Food: "White T4", Total: 4 }],
result = array.map(Object.values);

console.log(result);

如果您不依赖对象值的插入顺序,则可以使用显式键及其值。

ES6

var array = [{ Food: "Orange T1", Total: 3 }, { Food: "Blue T2", Total: 1 }, { Food: "Green T3", Total: 1 }, { Food: "White T4", Total: 4 }],
result = array.map(({ Food, Total }) => [Food, Total]);

console.log(result);

ES5

var array = [{ Food: "Orange T1", Total: 3 }, { Food: "Blue T2", Total: 1 }, { Food: "Green T3", Total: 1 }, { Food: "White T4", Total: 4 }],
result = array.map(function (o) { return [o.Food, o.Total]; });

console.log(result);

关于javascript - 如何在javascript中将json转换为数组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49433743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com