这里我附上了我的json。
"mainSteps": [
{
"id": "9b3b64b4-d8a5-46d5-b464-066dc5c45dc3",
"name": "Main Step 1",
"steps": [
{
"name": "sub step 1.1"
},
{
"name": "sub step 1.2"
}
]
},
{
"name": "Main step 2"
"steps": [
{
"name": "sub step 2.1"
},
{
"name": "sub step 2.2"
}
],
},
{
"name": "Main Step 3",
"steps": [
{
"name": "sub step 3.1"
},
{
"name": "sub step 3.2"
}
],
}
]
我正在寻找像 - >这样的输出[主要步骤1,子步骤1.1,子步骤1.2],[主要步骤2,子步骤2.1,子步骤2.2],[主要步骤3,子步骤3.1,子步骤3.2]。我花了一整天的时间来输出这个输出,但得到的输出像[[主要步骤1,主要步骤2,主要步骤3,子步骤1.1,子步骤1.2 ....]就像我得到不同的格式但我无法得到我提到的实际输出,有人可以澄清我。
var dataProcess = {
parentProcess:[],
subProcess:[]
};
var steps = mainData.steps; // Steps Having the Full json data
var proc = [];
$scope.getSteps = function(steps) {
for (var i=0;i< steps.length;i++) {
dataProcess.parentProcess.push(steps[i].name);
for(var j=i;j<steps[i].steps.length;j++){
dataProcess.subProcess.push(steps[i].steps[j].name);
}
}
这是我试过的方式之一,
答案 0 :(得分:2)
如果您需要ES5语法:
var details = mainSteps.map(function(step) {
return [ step.name ].concat((step.steps || []).map(function(substep){
return substep.name;
})
});
ES6语法:
var details = mainSteps.map(step =< [step.name].concat((step.steps || []).map(sub => sub.name));
如果你需要比一层深度更多的递归,你可以使用一个函数作为顶级映射器,它自己调用。
答案 1 :(得分:1)
可能你可以这样做;
var mainSteps = [
{
"id": "9b3b64b4-d8a5-46d5-b464-066dc5c45dc3",
"name": "Main Step 1",
"steps": [
{
"name": "sub step 1.1"
},
{
"name": "sub step 1.2"
}
]
},
{
"name": "Main step 2",
"steps": [
{
"name": "sub step 2.1"
},
{
"name": "sub step 2.2"
}
],
},
{
"name": "Main Step 3",
"steps": [
{
"name": "sub step 3.1"
},
{
"name": "sub step 3.2"
}
],
}
],
mapped = mainSteps.map(e => [e.name, e.steps[0].name, e.steps[1].name]);
console.log(mapped);
&#13;
答案 2 :(得分:1)
使用Array.map
和Array.concat
函数的简单解决方案:
// supposing "obj" is your initial object
var dataProcess = obj.mainSteps.map(function (o) {
return [o.name].concat(o.steps.map(function(v){ return v.name; }));
});
console.log(JSON.stringify(dataProcess, 0, 4));
输出:
[
[
"Main Step 1",
"sub step 1.1",
"sub step 1.2"
],
[
"Main step 2",
"sub step 2.1",
"sub step 2.2"
],
[
"Main Step 3",
"sub step 3.1",
"sub step 3.2"
]
]
答案 3 :(得分:1)
var results = mainSteps.map(x => [x.name].concat(x.steps.map(y => y.name)));