我有一个如下所示的对象数组,
var A = [
{
"111": ["A", "B", "C"]
},
{
"222": ["D", "E", "F"]
}
];
我想使用js或jQuery以如下所示的格式动态创建一个新数组。
数组A中的键应映射到AA的属性文本,值应为子项,如下所示
var AA = [
{
"text": "111",
"state": "open",
"children": [
{
"text": "A"
},
{
"text": "B"
},
{
"text": "C"
}]
},
{
"text": "222",
"state": "open",
"children": [
{
"text": "D"
},
{
"text": "E"
},
{
"text": "F"
}]
}];
我怎样才能做到这一点?任何想法都会有所帮助
感谢您的所有建议和帮助。 但是现在我想以下面的格式更改变量A和输入, 我怎么能像以前一样完成同样的事情。
var A = {"1":["1_1","1_2","1_3"],
"2":["2_1","2_2"],
"3":["3_1"],
"4":["4_1"],
"5":["5_1","5_2"]};
答案 0 :(得分:0)
您可以使用Array.prototype.map()
(两次)将A
映射到AA
。
var AA = A.map(function(item) {
var key = Object.keys(item)[0]; // this will be reliable only because each item has one property.
return {
'text': key,
'state': 'open',
'children': item[key].map(function(child) {
return { 'text': child };
})
};
});
<强> fiddle 强>
答案 1 :(得分:0)
我的答案太长了,但仍然可以理解
var A = [
{"111":["A","B","C"]},
{"222":["D","E","F"]}
];
console.log(A);
A = superGenerator(A);
console.log(A);
function superGenerator(data){
var dataF = [];
var children = [];
for (var i = data.length - 1; i >= 0; i--) {
children[i] = [];
for (var [key, val] of iterate_object(data[i])) {
for (var j = val.length - 1; j >= 0; j--) {
children[i][j] = [];
children[i][j] = {
text : val[j]
}
};
}
dataF[i] = {
text : Object.keys(data[i])[0],
state : 'open',
children : children[i]
}
};
return dataF;
}
function* iterate_object(o) {
var keys = Object.keys(o);
for (var i=0; i<keys.length; i++) {
yield [keys[i], o[keys[i]]];
}
}
进行尝试
干杯
答案 2 :(得分:0)
试试这个:
var A = [
{
"111": ["A", "B", "C"]
},
{
"222": ["D", "E", "F"]
}
];
var AA = A.map(item => {
return {
"text": Object.keys(item)[0],
"state": "open",
"children": item[Object.keys(item)[0]].map(elem => { return {"text": elem} })
}
});
console.log(AA);
&#13;
答案 3 :(得分:0)
您可以使用array#map
遍历数组,为每个对象迭代其所有键并生成相应的对象。
var arr = [ { "111": ["A", "B", "C"] }, { "222": ["D", "E", "F"] } ],
result = arr.map(o => Object.keys(o).reduce((r,k) => {
return {
text : k,
state : 'open',
children : o[k].map(text => ({text}))
};
},{}));
console.log(result);