循环不从数组中收集所有值

时间:2017-12-12 13:17:13

标签: javascript arrays loops object for-loop

我正在尝试创建一个一个接一个地工作的循环。我基本上试图从阵列中获得所有的成果。我试过在for循环中做一个for循环,但这只给了我每个对象的第一个水果而不是数组中的每一个水果。

withColumn

4 个答案:

答案 0 :(得分:2)

您的第二个for-loop 应该是items而不是customers

for(i=0; i < customers.length; i++) //notice that i < instead of i <=
{
   for(a=0; a < customers[i].Items.length; a++) //notice the change here
   {
     alert( customers[i].Items[a].Fruits ); // 
   }
}

更准确一点是使用reduce

var allFruits = customers.reduce( ( a, b ) => a.concat( b.Items.map( s => s.Fruits ) ) , []);

答案 1 :(得分:1)

您的第二个循环长度不正确。试试这个:

    var customers = [{
                "Name" : "John",
                "Items" :[{"Fruits" : "Apple"},{"Fruits" : "Orange"}]
            },{
                "Name" : "Sam",
                "Items" :[{"Fruits" : "Pear"},{"Fruits" : "Nuts"}]
            },{
                "Name" : "Eric",
                "Items" :[{"Fruits" : "Banana"},{"Fruits" : "Raisins"}]
            }];
 for(i=0; i<=customers.length; i++){
    for(a=0; a<=customers[i]["Items"].length; a++){
        alert(customers[i]["Items"][a]);
    }
}

答案 2 :(得分:1)

这可以解决您的问题。

&#13;
&#13;
var customers = [{
            "Name" : "John",
            "Items" :[
                {"Fruits" : "Apple"},{"Fruits" : "Orange"}]
            },{
                "Name" : "Sam",
            "Items" :[
                {"Fruits" : "Pear"},{"Fruits" : "Nuts"}]
            },{
                "Name" : "Eric",
            "Items" :[
                {"Fruits" : "Banana"},{"Fruits" : "Raisins"}]
            }];
 for(i=0; i<customers.length; i++){
 for(a=0; a<customers[i]["Items"].length; a++){
     console.log(customers[i]["Items"][a]);
 }
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

只需将concat方法与mapreduce结合使用即可轻松解决问题。

let fruits = [].concat(...customers.map(a => a.Items.map(b=>b.Fruits)));

&#13;
&#13;
var customers = [{ "Name" : "John", "Items" :[ {"Fruits" : "Apple"},{"Fruits" : "Orange"}] },{ "Name" : "Sam", "Items" :[ {"Fruits" : "Pear"},{"Fruits" : "Nuts"}] },{ "Name" : "Eric", "Items" :[ {"Fruits" : "Banana"},{"Fruits" : "Raisins"}] }];

let fruits = [].concat(...customers.map(a => a.Items.map(b=>b.Fruits)));
console.log(fruits);
&#13;
&#13;
&#13;

如果您想获得所有unique个水果,可以使用Set中的ES6

&#13;
&#13;
var customers = [{ "Name" : "John", "Items" :[ {"Fruits" : "Apple"},{"Fruits" : "Orange"}] },{ "Name" : "Sam", "Items" :[ {"Fruits" : "Pear"},{"Fruits" : "Nuts"}] },{ "Name" : "Eric", "Items" :[ {"Fruits" : "Banana"},{"Fruits" : "Raisins"}] }];
let fruits = [...new Set([].concat(...customers.map(a => a.Items.map(b=>b.Fruits))))];
console.log(fruits);
&#13;
&#13;
&#13;