Underscore.js - 通过对象数组循环

时间:2017-04-03 07:40:12

标签: javascript arrays json underscore.js

我有以下对象数组:

var products = [
    {
        id: 1,
        name: "Product 1",
        subTypes: [
            {
                id: 1,
                name: "Product 1 - Sub Type 1"
            },
            {
                id: 2,
                name: "Product 1 - Sub Type 2"
            }
        ]
    },
    {
        id: 2,
        name: "Product 2",
        subTypes: [
            {
                id: 1,
                name: "Product 2 - Sub Type 1"
            },
            {
                id: 2,
                name: "Product 2 - Sub Type 2"
            }
        ]
    }
];

使用underscore.js为什么以下的点符号不会将任何内容记录到控制台:

_.each(products.subTypes, function(subType) {
       console.log(subType.name);
 });

我只能通过嵌套foreach循环来实现它的工作原理如下?

_.each(products, function (product) {
    _.each(product.subTypes, function (subType) {
        console.log(subType.name);
    });
});

2 个答案:

答案 0 :(得分:0)

你可以检查一下

console.log('Subtypes:', products.subTypes.name);

答案 1 :(得分:0)

如果您想访问product.subTypes,您必须先从对象中提取它们。

这是你如何做到的。 3个示例函数:纯javascript,ES6,underscoreJS。



// pure JS
function pureJsloop(data) {
  var result = [];

  for (i = 0; i < data.length; i++) {
    var product = data[i];
    
    result.push(product.subTypes);

  }
  
  return result[0];
}

// ES6
function ES6loop(data) {
  // We are returning reduced array
  return data.reduce((previous, product) => {
    return previous = [ ...previous, product.subTypes ];
  }, [])[0];
}

// Underscore
function underscoreLoop(data) {

  return _.reduce(data, function(previous, product){ 
    return previous = [ ...previous, product.subTypes ];
  }, [])[0];
  
}


var products = [
              {
                id: 1,
                name: "Product 1",
                subTypes: [
                  {
                    id: 1,
                    name: "Product 1 - Sub Type 1"
                  },
                  {
                    id: 2,
                    name: "Product 1 - Sub Type 2"
                  }
                ]
              },
              {
                id: 2,
                name: "Product 2",
                subTypes: [
                  {
                    id: 1,
                    name: "Product 2 - Sub Type 1"
                  },
                  {
                    id: 2,
                    name: "Product 2 - Sub Type 2"
                  }
                ]
              }];
              


//console.log(pureJsloop(products));
//console.log(ES6loop(products));
console.log(underscoreLoop(products));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
&#13;
&#13;
&#13;