Подтвердить что ты не робот

Как использовать underscore.js для получения результата сглаживания

Объект 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
4b9b3361

Ответ 1

Здесь более короткое решение:

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

Ответ 2

В качестве альтернативы, если вы хотите использовать функцию, которая может повсеместно сгладить любую коллекцию объектов или массивов,

Вы можете расширить 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]) и вести себя точно так же, как обобщенная форма встроенного 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 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 .map is different
                                          // from plain Javascript in
          // _.map will always return     // that it will apply the passed
          // an array, which is why we    // function to an object 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.
  }
});

Надеюсь, это поможет, если кому-то это понадобится.:)

Ответ 3

Предполагая, что вы хотите сначала получить родителей, а затем получить детей:

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

Ответ 4

Если вы хотите использовать underScore.js, чтобы сгладить массив из множества массивов в один массив элементов, как вы это сделаете. Следуйте моему примеру:

Мой график имеет 2 серии. Каждая серия имеет имя и последовательность datapoints {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