[英]JSON - array of objects into objects of arrays
我有一系列JSON條目:
[{"num": "1","name_A": "Alex" ,"name_B": "Bob"}, {"num": "2","name_A": "Anne" ,"name_B": "Barbra"}]
我正在嘗試將對象數組盡可能輕松地轉換為兩個對象-一個對象的名稱為name_A,第二個對象的名稱為name_B。 對象必須包含標題和匹配的num-name對數組:
[{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,為什么沒有用於備忘錄的push方法?
第二個問題,我是在正確的道路上還是有更好的方法來實現這一目標?
您的代碼的問題是{ curr.num, curr.name_A }
不是有效的對象,它缺少屬性名稱。 我在下面的代碼中添加了屬性num
和name
。
var name_A = [];
var name_B = [];
objArray.forEach(function(curr) {
name_A.push({num: curr.num, name: curr.name_a});
name_B.push({num: curr.num, name: curr.name_B});
});
var result = [
{ title: "name_A" }, names: name_A },
( title: "name_B" }, names: name_B }
];
另外,如果要根據循環遍歷的結果制作數組,則應使用.map
而不是.reduce
。
內聯評論,對預期進行了一些小的更正。
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>
假設只有屬性num
是固定的。 所有其他屬性都被視為數據,例如name_A
或name_B
。
var a = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }], result = []; a.forEach(function (el) { var num = el.num; Object.keys(el).forEach(function (k) { function tryFindIndexAndSetNames(aa, i) { if (aa.title === k) { result[i].names[num] = el[k]; return true; } } if (k !== 'num' && !result.some(tryFindIndexAndSetNames)) { var o = {}; o[num] = el[k]; result.push({ title: k, names: o }); } }); }); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.