使用Lodash展平数组后,如何仅选择对象

时间:2019-01-04 11:25:39

标签: javascript lodash reducers

我已使用 lodash _.flatten展平了此数组,并使用化简器选择了对象类型。使用lodash的任何更好的方法。

sampleData = [ ["x", { "name" : "sam", "age": "20"}], ["y", { "name" : "andey", "age" : "26"}] , ["z", { "name" : "jon", "age" : "24"}]];
flattenData(sampleData ) {
    return _.flatten(sampleData ).reduce((flattenedArray, indexValue) => {
    typeof (indexValue) === 'object' ? flattenedArray.push(indexValue) : '';
    return flattenedArray;
    }, []);
} 

展平此数据后,需要拉出对象。有使用lodash的建议吗?

输出数组:

 [{ "name" : "sam", "age": "20"}, { "name" : "andey", "age" : "26"}, { "name" : "jon", "age" : "24"}]

4 个答案:

答案 0 :(得分:2)

您可以使用_.filter_.isObject方法仅返回对象数组。

使用_.chain方法const res = _.chain(data).flatten().filter(_.isObject).value()

const data = [ ["x", { "name" : "sam", "age": "20"}], ["y", { "name" : "andey", "age" : "26"}] , ["z", { "name" : "jon", "age" : "24"}]];
const res = _.filter(_.flatten(data), _.isObject)
console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

答案 1 :(得分:1)

使用简单的es6语法

减小捆绑包的大小:-)

const sampleData = [ ["x", { "name" : "sam", "age": "20"}], ["y", { "name" : "andey", "age" : "26"}] , ["z", { "name" : "jon", "age" : "24"}]];

const flattenedArray = [].concat(...sampleData).filter(e=>typeof(e)==='object');  
console.log(flattenedArray)

答案 2 :(得分:0)

或者,您可以迭代每个数组并将对象添加到数组累加器中。

let sampleData = [ ["x", { "name" : "sam", "age": "20"}], ["y", { "name" : "andey", "age" : "26"}] , ["z", { "name" : "jon", "age" : "24"}]],
    result = sampleData.reduce((r, a) => {
      a.forEach(o => o === Object(o) && r.push({...o}));
      return r;
    },[]);
console.log(result);

答案 3 :(得分:0)

使用_.flatMap()_.last()作为迭代项展平:

const data = [ ["x", { "name" : "sam", "age": "20"}], ["y", { "name" : "andey", "age" : "26"}] , ["z", { "name" : "jon", "age" : "24"}]];

const result = _.flatMap(data, _.last);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

或本机js Array.flatMap()(IE和Edge不支持):

const data = [ ["x", { "name" : "sam", "age": "20"}], ["y", { "name" : "andey", "age" : "26"}] , ["z", { "name" : "jon", "age" : "24"}]];

const result = data.flatMap(([, o]) => o);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>