简体   繁体   English

过滤Javascript对象数组

[英]Filtering Javascript object array

I am trying to get a new array object based on two of them. 我试图基于其中两个获取新的数组对象。

log1 = {1:"London",2:"New york",4:"Berlin"};
log2 = [{id:1, location:"EU"},{id:2, location:"US"},{id:18, location:"Asia"}];

I want to make sure that log1 keys all exist in log2 and, if not, I want to delete it. 我想确保log1键全部存在于log2中,如果不存在,我想将其删除。 So for this will be: 因此,这将是:

 result = {1:"London",2:"New york"};

I couldn't do it with filter as it take only one object. 我无法使用过滤器来做,因为它只带一个对象。 Is there any way to filter based on two object arrays? 有什么办法可以基于两个对象数组进行过滤吗? Is there any neat way to do it ? 有什么整洁的方法吗?

Here is how you can do it in pure js: 这是您可以在纯js中完成的方法:

    log1 = {1:"London",2:"New york",4:"Berlin"};
    log2 = [{id:1, location:"EU"},{id:2, location:"US"},{id:18, location:"Asia"}];

    for (var prop1 in log1) {
        var found = false;
        for (var i = 0; i < log2.length; i++) {
            if (log2[i].id.toString() === prop1) {
                found = true;
                break;
            }
        }
        if (!found) {
            delete log1[prop1]
        }
    }

If you are using a recent version of JS with Array.map() , Array.filter() and Object.keys() you could try the following for a slightly more functional approach: 如果您使用的是带有Array.map()Array.filter()Object.keys()的最新版本的JS, Array.map()可以尝试以下方法来获得更实用的方法:

var log1 = {
    1: "London",
    2: "New york",
    4: "Berlin"
};

var log2 = [
    {id: 1,  location: "EU"},
    {id: 2,  location: "US"},
    {id: 18, location: "Asia"}
];


var ids = log2.map(function(obj) { return obj.id; }).map(String);

Object.keys(log1).filter(function(key) {
    return ids.indexOf(key) === -1;
}).forEach(function(k) {
    delete log1[k];
});

console.log(log1);

Should yield: 应该产生:

{ '1': 'London', '2': 'New york' }

Example: http://repl.it/RnF/2 示例: http//repl.it/RnF/2

Hope this helps :) 希望这可以帮助 :)

Edit 编辑

Otherwise, for browser compatibility and much more you could consider lodash or underscore as suggested by other posters. 否则,出于浏览器兼容性的考虑,您可以考虑其他海报建议的lodash或下划线。 Or use a polyfill! 或使用polyfill!

MDN provides polyfills at the bottom of each of the following pages for older environments (in case you require the compatibility): 对于较旧的环境(如果需要兼容性),MDN在以下每个页面的底部提供了polyfill:

Use http://underscorejs.org/ 使用http://underscorejs.org/

It has pluck,filter and map functions that can help you out.. Its quite powerful.. 它具有摘录,筛选和映射功能,可以帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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