如何使用underscore.js生成flatten结果

时间:2012-01-09 09:43:28

标签: javascript json underscore.js

json对象是

var data = [{"Parent":1,"Child":[4,5,6]},{"Parent":2},{"Parent":3}]

如何使用underscore.js链/ map / pluck等...函数来获得扁平化结果

     var result = [];
for (var i = 0; i < data.length; i++) {
    result.push(data[i].Parent);
    if (data.Child != undefined) {
        for (var j = 0; j < data[i].Child.length; j++) {
            result.push(data[i].Child[j]);
        }
    }
}
console.log(result) >> //1,4,5,6,2,3

4 个答案:

答案 0 :(得分:46)

这是一个较短的解决方案:

flat = _.flatten(_.map(data, _.values)) 

答案 1 :(得分:14)

或者,如果您想要一个可以普遍展平任何对象或数组集合的函数,

您可以使用以下内容扩展Underscore:

_.mixin({crush: function(l, s, r) {return _.isObject(l)? (r = function(l) {return _.isObject(l)? _.flatten(_.map(l, s? _.identity:r)):l;})(l):[];}});

粉碎(缺少更好的名称)可以像_.crush(list, [shallow])_(list).crush([shallow])一样调用,其行为与Underscore的内置 Flatten的广义形式完全相同

它可以传递任何深度的嵌套对象,数组或两者的集合,并返回包含所有输入值和自身属性的单层数组。与展平一样,如果传递一个额外的参数,其值为true,则执行“浅”执行,输出仅展平一个级别。

示例1:

_.crush({
   a: 1,
   b: [2],
   c: [3, {
      d: {
         e: 4
      }
   }]
});

//=> [1, 2, 3, 4]

示例2:

_.crush({
   a: 1,
   b: [2],
   c: [3, {
      d: {
         e: 4
      }
   }]
}, true);

//=> [1, 2, 3, {
//      d: {
//         e: 4
//      }
//   }]

代码本身的解释如下:

_.mixin({  // This extends Underscore's native object.

  crush: function(list, shallow, r) {  // The "r" is really just a fancy
                                       // way of declaring an extra variable
                                       // within the function without
                                       // taking up another line.

    return _.isObject(list)?  // Arrays (being a type of object)
                              // actually pass this test too.

      (r = function(list) {  // It doesn't matter that "r" might have
                             // been passed as an argument before,
                             // as it gets rewritten here anyway.

        return _.isObject(list)?  // While this test may seem redundant at
                                  // first, because it is enclosed in "r",
                                  // it will be useful for recursion later.

          _.flatten(_.map(list, shallow?  // Underscore's .map is different
                                          // from plain Javascript's in
          // _.map will always return     // that it will apply the passed
          // an array, which is why we    // function to an object's values
          // can then use _.flatten.      // as well as those of an array.

            _.identity  // If "shallow" is truthy, .map uses the identity
                        // function so "list" isn't altered any further.

            : r  // Otherwise, the function calls itself on each value.
          ))
          : list  // The input is returned unchanged if it has no children.
        ;
      })(list)  // The function is both defined as "r" and executed at once.

      : []  // An empty array is returned if the initial input
    ;       // was something other than an object or array.
  }
});

希望如果有人需要它会有所帮助。 :)

答案 2 :(得分:11)

假设你想首先得到父母,然后让孩子们接受:

_.chain(data).pluck("Parent")
             .concat(_.flatten(_(data).pluck("Child")))
             .reject(_.isUndefined)
             .value()

答案 3 :(得分:0)

如果要使用underScore.js将多个数组的数组展平为一个元素数组,那么就是这样做的。按照我的例子:

我的图表有2个系列。每个系列都有一个名称和一系列数据点{xtime,yValue}。我的目标是将所有数据点从2个系列中分解为一系列数据点,以便填写表格。

var reducedArray = // flatten an array of series of data-objects into one series of data-objects
_.flatten( _.map( AllMySeries, function ( aSeries ) {
    return ( _.map( aSeries.dataPoints, function ( aPoint ) {
                return { curveID: aSeries.legendText, xT: aPoint.x, yVal: aPoint.y };
            } ) );
} ) );

我的结果:

'Series1','2017-04-19 08:54:19',1
'Series1','2017-04-19 08:59:19',0
'Series1','2017-04-19 09:04:19',1
'Series2','2017-04-19 08:54:19',1
'Series2','2017-04-19 08:59:19',0
'Series2','2017-04-19 09:04:19',1