javascript forEach多功能数组

时间:2017-10-23 08:20:16

标签: javascript arrays json foreach

我有源代码,如何仅输出forEach arrise.tester2或者输出JSON字符串呢? 这是代码:

var arrise = [{"tester1":"testo","tester2":["testi1","testi2"]},{"tester1":"testc","tester2":["test1","test2"]},{"tester1":"testd","tester3":["tes1","tes3"]}];  

2 个答案:

答案 0 :(得分:1)

您可以使用array#maparray#filter。访问数组中的每个对象,然后检查tester2键。



var arrise = [{"tester1":"testo","tester2":["testi1","testi2"]},{"tester1":"testc","tester2":["test1","test2"]},{"tester1":"testd","tester3":["tes1","tes3"]}];

var result = arrise
              .map(o => o.tester2)
              .filter(x => x);
console.log(result);




答案 1 :(得分:0)

您可以首先通过检查属性进行过滤,然后映射值。



var arrise = [{ tester1: "testo", tester2: ["testi1", "testi2"] },{ tester1: "testc", tester2: ["test1", "test2"] }, { tester1: "testd", tester3:["tes1", "tes3"] }],
    tester2 = arrise
        .filter(o => o.tester2)
        .map(o => o.tester2);

console.log(tester2);