gpt4 book ai didi

javascript - JSON - 对象数组到数组对象

转载 作者:行者123 更新时间:2023-11-30 16:31:10 25 4
gpt4 key购买 nike

我有一系列的 JSON 条目:

[{"num": "1","name_A": "Alex" ,"name_B": "Bob"}, {"num": "2","name_A": "Anne" ,"name_B": "Barbra"}]

我试图尽可能轻松地将这个对象数组转换为两个对象 - 一个标题为 name_A,第二个标题为 name_B。对象必须包含标题和一组匹配的数字名称对:

[{title: "name_A", names:[{"1", "Alex}, {"2", "Anne"}]}, {title:"name_B", names: [{"1", "Bob"}, {"2", "Barbra"}]}]

起初我尝试简单地通过减少对象数组两次来创建两个对象,一次用于 name_A,第二次用于 name_B,然后将所有内容粘合在一起:

// get 'names' array
var name_A = objArray.reduce(function(memo, curr) {
memo.push({curr.num, curr.name_A})
return memo;
}, []);

但即使这样也是失败的。为什么我用空数组初始化 reduce 就没有 memo 的 push 方法?

第二个问题,我走在正确的轨道上还是有更好的方法来实现这一目标?

最佳答案

内联评论,对预期进行了一些小的修正。

var input = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }]

var output = input.reduce(function (a, b) {
// construct new objects and set their properties
var i = {};
i[b.num] = b.name_A;
var j = {};
j[b.num] = b.name_B;

// add them to our collection elements
a[0].names.push(i);
a[1].names.push(j);

return a;
// initializing our collection
}, [{ title: "name_A", names: [] }, { title: "name_B", names: [] }]);

// pretty print our output
console.log(JSON.stringify(output, null, " "))

var input = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }]

var output = input.reduce(function (a, b) {
// construct new objects and set their properties
var i = {};
i[b.num] = b.name_A;
var j = {};
j[b.num] = b.name_B;

// add them to our collection elements
a[0].names.push(i);
a[1].names.push(j);

return a;
// initializing our collection
}, [{ title: "name_A", names: [] }, { title: "name_B", names: [] }]);

so.log(output)
<pre id="output"></pre>
<script>
var so = {
log: function(o) {
document.getElementById("output").innerHTML = JSON.stringify(o, null, " ")
}
}
</script>

关于javascript - JSON - 对象数组到数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33307017/

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