这就是我的......
[{
"programName": "Testing 102",
"recommendedComparisons": [{
"programName": "Testing 101",
"id": 2
}, {
"programName": "Testing 401",
"id": 4
}],
"id": 1,
"programId": 3
}, {
"programName": "Testing 101",
"recommendedComparisons": [{
"programName": "Testing 102",
"id": 3
}],
"id": 9,
"programId": 2
}]
我想要的是两个推荐比较列表。
Testing 101, Testing 401
和Testing 102
我确定必须有简单的方法。
答案 0 :(得分:0)
var data = [{
"programName": "Testing 102",
"recommendedComparisons": [{
"programName": "Testing 101",
"id": 2
}, {
"programName": "Testing 401",
"id": 4
}],
"id": 1,
"programId": 3
}, {
"programName": "Testing 101",
"recommendedComparisons": [{
"programName": "Testing 102",
"id": 3
}],
"id": 9,
"programId": 2
}];
var result = data.map(function(item) {
return item.recommendedComparisons.map(function(comp) {
return comp.programName;
});
});
答案 1 :(得分:0)
您要找的是数组对象的地图功能。
您正在寻找推荐比较的程序名称。为此,你需要1个map函数来进行比较,然后你需要再次调用map,并在子函数中调用map来返回程序名称。
由于您提到了逗号分隔列表,最好不要返回数组本身。而是创建一个新字符串,并用逗号连接子数组,并用新行附加它。
我相信这就是你要找的东西
var array = [{"programName":"Testing 102","recommendedComparisons":[{"programName":"Testing 101","id":2},{"programName":"Testing 401","id":4}],"id":1,"programId":3},{"programName":"Testing 101","recommendedComparisons":[{"programName":"Testing 102","id":3}],"id":9,"programId":2}]
var results = array.map(function(a) { return a.recommendedComparisons
}).map(function(b) {
return b.map(function(c) {
return c.programName;
});
});
var str = "";
for (var i = 0; i < results.length; i++) {
str += results[i].join(',') + "\n"
}
console.log(str);
&#13;
答案 2 :(得分:0)
利用map
函数可以转换对象。
var recommendedComparisons = data.map(x =>
x.recommendedComparisons.map(x=>x.programName));
使用Destructuring获取2个结果列表。
var [firstList,secondList] = recommendedComparisons;
var data = [{
"programName": "Testing 102",
"recommendedComparisons": [{
"programName": "Testing 101",
"id": 2
}, {
"programName": "Testing 401",
"id": 4
}],
"id": 1,
"programId": 3
}, {
"programName": "Testing 101",
"recommendedComparisons": [{
"programName": "Testing 102",
"id": 3
}],
"id": 9,
"programId": 2
}];
var recommendedComparisons = data.map(x => x.recommendedComparisons.map(x=>x.programName));
var [firstList,secondList] = recommendedComparisons;
console.log(firstList);
console.log(secondList);
&#13;
答案 3 :(得分:0)
我还没有测试过,但我很确定这是对的。我现在要测试一下。
const list = [
{
"programName":"Testing 102",
"recommendedComparisons":[
{ "programName": "Testing 101", "id":2 },
{ "programName": "Testing 401", "id":4 }
],
"id":1,
"programId":3
},
{
"programName":"Testing 101",
"recommendedComparisons":[
{"programName":"Testing 102","id":3}
],
"id":9,
"programId":2
}
];
let listOfComparisonLists = [];
list.map((program) => {
const programNames = program.recommendedComparisons.map((comp) => comp.programName);
listOfComparisonLists.push(programNames);
});
console.log(listOfComparisonLists); // [['Testing 104', 'Testing 401'],['Testing 102']]