最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Combine nested arrays into one? - Stack Overflow

programmeradmin2浏览0评论

Let's say I have an array of objects that look similar to this:

[
   {
     id: ...,
     name: "...",
     users: [1, 2, 3]
    },
    ...
]

Is there a way that I can easily merge the .users array of each object into one array?

Let's say I have an array of objects that look similar to this:

[
   {
     id: ...,
     name: "...",
     users: [1, 2, 3]
    },
    ...
]

Is there a way that I can easily merge the .users array of each object into one array?

Share Improve this question asked Apr 29, 2015 at 21:37 m0ngr31m0ngr31 8301 gold badge16 silver badges31 bronze badges
Add a comment  | 

7 Answers 7

Reset to default 9

Pluck 'n' flatten will do what you want:

var result = _.flatten(_.pluck(data, 'users'));

Edit

As Richard points out, pluck was removed from lodash in version 4.0.0 but still remains in the current version of underscore at time of writing (1.8.3).

Replacing pluck with map works for both lodash and underscore:

var result = _.flatten(_.map(data, 'users'));

Do not know lodash or underscore, but you can use the native forEach and concat methods of Array (underscore may have equivalent methods, and polyfills for older browsers)

var data = [{
     id: ...,
     name: "...",
     users: [1, 2, 3]
    },
    ...
];
var allUsers = [];
data.forEach(function(obj){
   allUsers = allUsers.concat(obj.users);
});

console.log(allUsers);

Demo

var data = [{
     id: 1,
     name: "...",
     users: [1, 2, 3]
    },
    {
     id: 2,
     name: "....",
     users: [4, 5, 6]
    },
    {
     id: 3,
     name: "...",
     users: [7, 8, 9]
    },            
];
var allUsers = [];
data.forEach(function(obj){
   allUsers = allUsers.concat(obj.users);
});

document.querySelector("#log").innerHTML = allUsers.join(",");
<div id="log"></div>

Using lodash:

var objects = [
   {
     id: "...",
     name: "...",
     users: [1, 2, 3]
    },
   {
     id: "...",
     name: "...",
     users: [4, 5, 6]
    },
    //...
];
var allUsers = _.flatMap(objects, function(o){return o.users;});

console.log(allUsers);
// allUsers: [1,2,3,4,5,6]
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

This will loop through the original array and return a new array that only contains the values of the users arrays. I'm using Array.prototype.reduce to keep everything contained but you could technically just do it with a for loop too.

var data = [{id: 1, name: "A", users: [1, 2, 3]},
            {id: 2, name: "B", users: [4, 5, 6]},
            {id: 3, name: "C", users: [7, 8, 9]}];
var allUsers = data.reduce(function (result, current) {
    Array.prototype.push.apply(result, current.users);
    return result;
}, []);

The reason I use Array.prototype.push is so that I'm modifying an existing array instead of creating multiple copies (by using something like Array.prototype.concat).

You can use the Array.prototype.push method:

var res = [];
for (var i = 0; i < o.length; i++) {
   res.push.apply(res, o[i].users);
}

If the array should contain unique elements:

res = res.filter(function(val, i, arr) { 
    return arr.indexOf(val) === i;
});
var a = [
   {
     id: 1,
     name: "...",
     users: [1, 2, 3]
    },
    ...
];
var res = new Array();
for(var i = 0; i < a.length; i++) {
    a[i].users.forEach(function(val) { res.push(val); }
);

This may not be the most effecient, but it will accomplish what your after.

See fiddle here: http://jsfiddle.net/TylersDesk/3x1w8y95/

var objects = [
    {
        time: 1234,
        users: ["Joe", "Bob", "Blake"]
    },
    {
        time: 1234,
        users: ["Annie", "Gale"]
    }
]

var allUsers = []

for (i=0; i<objects.length; i++) {
    for (key in objects[i]) {
        if (key === "users") {
            console.log('found users');
            console.log(objects[i][key]);

            for (g=0; g<objects[i][key].length; g++) {
                console.log(objects[i][key][g]);

                //Add to array
                allUsers.push(objects[i][key][g]);          
            }
        }
    }
}

//Output all users
console.log(allUsers);
发布评论

评论列表(0)

  1. 暂无评论