如果我有这样的对象:
"names" :
{
'name1' : 'Mike',
'name2' : 'Tom',
..}
"numbers" :
{
'number1' : 'b1',
'number2' : 'b2',
..}
"levels" :
{
'level1' : '0',
'level2' : '0',
...
}
如何创建三个单独的对象,如:
declare variable $testseq as item()* := ();
declare function local:insertseq($target as item()*, $position as xs:integer?, $inserts as item()*)
as item()* (:might be great if we have a keyword to represent nothing:)
{
fn:insert-before($target, 1, $inserts) (:change the global sequence:)
() (:simulate returning nothing, empty sequence:)
};
element test
{
attribute haha {"&"},
local:insertseq($testseq, 1, ('a', 'b')),
$testseq
}
答案 0 :(得分:1)
您可以使用键和元素迭代的数量作为属性。
var myObj = [{ 'name': 'Mike', 'number': 'b1', 'level': 0 }, { 'name': 'Tom', 'number': 'b2', 'level': 0 }],
result = {};
myObj.forEach(function (a, i) {
Object.keys(a).forEach(function (k) {
result[k + 's'] = result[k + 's'] || {};
result[k + 's'][k + (i + 1)] = a[k];
});
});
console.log(result);

答案 1 :(得分:1)
使用Object.keys
函数,ES6箭头函数表达式和预定义parts
对象的替代解决方案:
var myObj = [{'name': 'Mike', 'number': 'b1', 'level': 0},{'name': 'Tom', 'number': 'b2', 'level': 0}],
parts = {'names': {}, 'numbers': {}, 'levels': {}};
myObj.forEach(function(obj, i){
Object.keys(obj).forEach((k) => (parts[k +"s"][k +(i+1)] = obj[k]));
});
console.log(JSON.stringify(parts, 0, 4));
输出:
{
"names": {
"name1": "Mike",
"name2": "Tom"
},
"numbers": {
"number1": "b1",
"number2": "b2"
},
"levels": {
"level1": 0,
"level2": 0
}
}
答案 2 :(得分:0)
JS objects
中的密钥必须为unique
。
name : Tom
的后续声明会覆盖您之前的声明。
代码:
var newObj = {};
newObj.names = {};
newObj.numbers = {};
newObj.levels = {};
for (var i in myObj) {
newObj.names.name = myObj[i].name;
newObj.numbers.number = myObj[i].number;
newObj.levels.level = myObj[i].level;
}
console.log(newObj);
演示小提琴:https://jsfiddle.net/29pb33dj/
使用索引的正确键更新了答案:
var newObj = {};
newObj.names = {};
newObj.numbers = {};
newObj.levels = {};
for (var i in myObj) {
newObj.names[i] = myObj[i].name;
newObj.numbers[i] = myObj[i].number;
newObj.levels[i] = myObj[i].level;
}
console.log(newObj);