使用 _Underscore 从嵌套对象创建值数组

Create array of values from a nested object using _Underscore

我费了好大劲才弄明白这个问题。 _Underscore JS 仍然相对较新,我正在尝试从嵌套对象数组创建一个唯一值数组。以下示例数据:

[  
   {  
      "property":"prop1",
      "list":[  
         {  
            "description":"description blah",
            "type":"F",
            "values":{  
               "value1":30.0,
               "value2":0.0
            }
         },
         {  
            "description":"description blah",
            "type":"F",
            "values":{  
               "value1":30.0,
               "value2":0.0
            }
         }
      ]
   },
   {  
      "property":"prop2",
      "list":[  
         {  
            "description":"description blah",
            "type":"Q",
            "values":{  
               "value1":30.0,
               "value2":0.0
            }
         }
      ]
   }
]

我试图取回的是一个包含所有唯一嵌套 "type" 值的数组。下面的数据示例:

["F","Q"]

我尝试了 _.pluck_.map 但收效甚微。我是否需要使用不同的东西,例如链接它们?感谢我能得到的任何帮助。

你可以做这个普通的 JS 和 reduce(抱歉,我对下划线不是很熟悉,所以我想我现在会提供一个普通的解决方案)

var uniqueValues = data.reduce(function(vals, d) {
    return vals.concat(d.list.reduce(function(listVals, l) {
        if (vals.indexOf(l.type) === -1 && listVals.indexOf(l.type) === -1) {
            listVals.push(l.type)
        }

        return listVals;
    }, []))
}, [])

演示:https://jsfiddle.net/0dsdm7Lu/

_.unique(_.flatten(_.map(myList, item => _.map(item.list, i => i.type))));

Underscore 在组合函数时并不是最好的,因为它首先获取数据。 lodash-fpramda 在这方面要好得多。

工作fiddle:https://jsfiddle.net/8eLk7t15/

这是一个使用链接的解决方案:

let result = _.chain(data)
    .pluck('list')
    .flatten()
    .pluck('type')
    .uniq()
    .value();

这首先 plucking the lists from the data and flattening them. Then the type is plcuked from the list before finally calling uniq 获得唯一类型。