在Javascript对象中查找属性的交集 [英] Finding the intersection of properties in Javascript objects

查看:97
本文介绍了在Javascript对象中查找属性的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我想我有两个对象

Hi guys suppose I have following two objects

var obj1 = {one:232,two:3123,three:3232}
var obj2 = {one:323,three:3444,seven:32}

我正在尝试编写一个函数,它将返回两个对象中的属性,假设我将始终有两个对象作为参数。因此,对于我的输出,看到 [one,three] 非常棒。

I am trying write a function that will return the properties that are in both objects, assuming that I will always have two objects as arguments. So for my output it'd be awesome to see ["one","three"].

这里是我写的是什么

var extend = function(obj){ 
    var x = Object.keys(arguments[0]);
    var y = Object.keys(arguments[1]);
    var inter =[];
    for(var i = 0; i < x.length; i++){
        for(var k = 0; k < y.length;i++){
            if(x[i] === y[k]) {
                inter.push(y[k]);
            }

            }
        }
    return inter;   
}

我期望这样做是为了创建两个属性的数组对象并检查每一对以查看它们是否相等。如果它们是我希望它将常见项目推送到新阵列。出于某种原因,这不会运行,因为它似乎无限期地运行。

What I expected this to do was to create an array of the properties of both of the objects and check each pair to see if they are equal. If they are I wanted it to push the common items into a new array. For some reason, this doesn't run because it seems to be running indefinitely.

任何人都可以帮忙吗?

推荐答案

让自己轻松自如 -

Make it easy on yourself-

Object.keys返回一个数组,你可以使用数组过滤器。

Object.keys returns an array, you can use array filter.

var commonproperties= function(o1, o2){
    return Object.keys(o1).filter(function(itm){
        return itm in o2
    });
}

var obj1 = {one:232,two:3123,three:3232},
obj2 = {one:323,three:3444,seven:32};
commonproperties(obj1 ,obj2);

/*  returned value: (Array)
['one','three']
*/

这篇关于在Javascript对象中查找属性的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆