Javascript 对象映射(展平)

Javascript Object Map (flatten)

您好,我有一个使用 JSON.Stringify

输出到此的对象
{"0":["test1","ttttt","","","","","","","",""],"1":["test2","ghjgjhgjh","","","","","","","",""]}

我想要这样的输出。

[["test1","ttttt","","","","","","","",""],["test2","ghjgjhgjh","","","","","","","",""]]

我试过使用 .map

删除“0”和“1”
var itemjson = $.map(cleanedGridData, function (n) {
        return n;
    });

然而,这给出了(下图)的输出,它已经变平了。

["test1", "ttttt", "", "", "", "", "", "", "", "", "test2", "ghjgjhgjh", "", "", "", "", "", "", "", ""]

更改您的 return 语句以将 n 放入另一个数组。

return [n];

这是因为 jQuery 的 $.map 将您 return 的数组扁平化为结果,因此您需要将其包裹在外部数组中。

要么,要么只使用 for in 循环。

var itemjson = [];
for (var key in cleanedGridData) {
  itemjson.push(cleanedGridData[key]);
}

您可以使用它来提取值:

var res = {"0":["test1","ttttt","","","","","","","",""],"1":["test2","ghjgjhgjh","","","","","","","",""]}
Object.keys(res).map(function(key) {
    return res[key];
});

Object.keys 将列出初始对象中的所有键。然后,您可以使用 map 遍历这些键并在该函数中提取值。

一旦您的环境(即在浏览器的情况下,您想要支持的所有浏览器)都有 Object.values (and spread operator)可用,您可以去

[...Object.values(cleanedGridData)]