简体   繁体   中英

Merge property values of 2 objects into an array using underscore chain

I have the following:

a = {x:1, y:3, w:4}
b = {c:2, d:3}

And I want to obtain all the values of these objects iterating only once.

result = [1, 3, 4, 2, 3]

I have the following solution but it has multiple iterations.

result = _.chain(a).values().union(_.values(b)).value();

I would like to avoid the "_.values(b)" and do this using the same chain from a.

I also tried this, but it is not working properly:

result = _.chain({}).extend(a,b).values().value();

If you're intent on chaining, then

_.chain([a, b])   .         // [ { x: 1, y: 3, w: 4 }, { c: 2, d: 3 } ]
    map(_.values) .         // [ [    1,    3,    4 ], [    2,    3 ] ]
    flatten()     .         // [      1,    3,    4,        2,    3   ]
    uniq()        .         // [      1,    3,    4,        2         ]
    value()

How about.

var a = {x:1, y:3, w:4},
    b = {c:2, d:3};

result = _.values(_.extend(a,b));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM