我是javascript和json的新手。我有一个像下面这样的对象数组:
let data = [
{
"build_name":"name1",
"build_type":"element",
"info":{
"element":"testvalue",
"repository":"mag",
"version":123
}
},
{
"build_name":"name2",
"build_type":"element",
"info":{
"element":"abcd",
"repository":"uuuuu",
"version":"ttttt"
}
}
];
我循环创建以下的对象, 期望输出:
{
"build":{
"name1":{
"type":"element",
"info":{
"element":"testvalue",
"repository":"mag",
"version":123
}
},
"name2":{
"type":"element",
"info":{
"element":"abcd",
"repository":"uuuuu",
"version":"ttttt"
}
}
}
}
但是我得到了一些无效格式的错误。我尝试使用以下方法使其工作,但没有成功,
let test = [];
data.forEach(function (arr) {
let test2 = {
[arr.build_name]: {
"type": arr.build_type
},
"info": {
"element": arr.info.element,
"repository": arr.info.repository,
"version": arr.info.version
}
}
test.push(test2);
});
console.log(JSON.stringify(test));
let val =
{"build" : {
test
}
}
console.log(val);
有没有办法实现这个?非常感谢任何帮助。
JSFiddle - https://jsfiddle.net/c9dxjgrt/
let data = [{
"build_name": "name1",
"build_type": "element",
"info": {
"element": "testvalue",
"repository": "mag",
"version": 123
}
},
{
"build_name": "name2",
"build_type": "element",
"info": {
"element": "abcd",
"repository": "uuuuu",
"version": "ttttt"
}
}
];
let test = [];
data.forEach(function(arr) {
let test2 = {
[arr.build_name]: {
"type": arr.build_type
},
"info": {
"element": arr.info.element,
"repository": arr.info.repository,
"version": arr.info.version
}
}
test.push(test2);
});
console.log(JSON.stringify(test));
let val = {
"build": {
test
}
}
console.log(val);
build_name
的副本,但问题暗示这是可以接受的。 - Arrmaniac