如何使用 underscore.js 产生扁平化结果

发布于 2024-12-25 19:24:34 字数 489 浏览 4 评论 0原文

json 对象是

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

如何使用 underscore.js chain/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

The json object is

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

How can I use underscore.js chain/map/pluck etc... function to get the flatten result

     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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

戒ㄋ 2025-01-01 19:24:34

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

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

Here's a shorter solution:

flat = _.flatten(_.map(data, _.values)) 
旧夏天 2025-01-01 19:24:34

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

您可以使用以下方式扩展 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(由于缺乏更好的名称)可以像 _.crush 一样调用(list, [shallow])_(list).crush([shallow]) ,其行为与 Underscore 内置 Flatten 的通用形式完全相同。

它可以传递任意深度的嵌套对象、数组或两者的集合,并将返回一个包含所有输入值和自己的属性的单级数组。与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.
  }
});

希望对需要的人有所帮助。 :)

Alternatively, if you want a function that can universally flatten any collection of objects or arrays,

You could extend Underscore with:

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

Crush (for lack of a better name) can be called like _.crush(list, [shallow]) or _(list).crush([shallow]) and behaves exactly like a generalized form of Underscore's built-in Flatten.

It can be passed a collection of nested objects, arrays, or both of any depth and will return a single-leveled array containing all of the input's values and own properties. Like Flatten, if it is passed an additional argument which evaluates to true, a "shallow" execution is performed with the output only flattened one level.

Example 1:

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

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

Example 2:

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

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

An explanation of the code itself is as follows:

_.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.
  }
});

Hope it helps if anyone needs it. :)

乖乖 2025-01-01 19:24:34

假设您想先获取父母,然后获取孩子:

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

Assuming you want to first get the parents and then get the children:

_.chain(data).pluck("Parent")
             .concat(_.flatten(_(data).pluck("Child")))
             .reject(_.isUndefined)
             .value()
指尖上的星空 2025-01-01 19:24:34

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

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

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  

If you want to use underScore.js to flatten an array of many arrays into one array of elements, that's how you do it. Follow my example:

My graph has 2 series. Each series has a name and a sequence of datapoints {xtime, yValue}. My goal is to iron out all the data points from 2 series into one series of data points so to fill out a table.

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 };
            } ) );
} ) );

My result :

'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  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文