繁体   English   中英

从对象数组获取键值数组,而又不知道对象数组的格式(Javascript)?

[英]Get array of key-values from array of objects without knowing format of array of objects (Javascript)?

想象一下,我给了类似对象数组的引用,例如array将是该array的名称。 现在,我被要求创建一个数组,该数组包含在该数组的每个对象内找到的某个属性的所有值,例如"user.id"

问题是我不知道每个对象的格式以及该属性的驻留位置/嵌套位置。因此"user.id"可能驻留在array[#].someKeyarray[#].someKey["user.id"] )或在array[#].someKey.someOtherKeyarray[#].someKey.someOtherKey["user.id"] )中

是否有可以创建此类数组的函数(jQuery,下划线..etc)? 例如var arrayOfUserIds = returnArray(array, "user.id");

例如,假设以下是此类数组的示例:

var array = [
{
  "age": "13",
  "type": "publish_action",
  "tag": null,
  "timestamp": 1398931707000,
  "content": {
    "action": "publish",
    "user.id": "860",
    "user.email": "alex@somemail.com",
    "property.id": "2149",
    "iteration_id": "15427",
    "test_id": "6063",
    "property.name" : "bloop"
}, {
  ....
}, {
  ....
}];

基于以上所述,我显然可以做到:

var arrayOfUserIds = [];

for (var i=0; i<array.length; i++)
{
  arrayOfUserIds.push(array[i]["content"]["user.id"]);
}

但是就像我说的那样,就我而言,我不知道对象的格式,因此无法创建这样的for循环。

任何想法将不胜感激!

谢谢!

如果我理解正确的话, someArray每个对象要么包含一个属性user.id要么包含一个包含user.id的对象……或者递归地,某个对象包含someArray 您要创建一个仅包含user.id属性的数组。

一种简单的方法是对数组中的每个对象进行递归检查,直到找到user.id

// get `user.id` property from an object, or sub-object
// it is assumed that there will only be one such property;
// if there are more than one, only the first one will be returned
function getUserId(o){
    if(o===null || o===undefined) return;
    if(o['user.id']) return o['user.id'];
    for(var p in o){
        if(!o.hasOwnProperty(p)) continue;
        if(typeof o[p] !== 'object') continue;
        if(o[p] === null || o[p] === undefined) continue;
        var id = getUserId(o[p]);
        if(id) return id;
    }
}

function getUserIds(arr){
    return arr.map(function(e){
        return getUserId(e);
    });
}

如果您想要一些通用的东西,可以编写“ find”方法,该方法将在对象树中找到命名属性的所有实例:

 var find = (function(){
    function find(matches, o, prop, checkPrototypeChain){
        if(typeof o[prop] !== 'undefined') matches.push(o[prop]);
        for(var p in o){
            if(checkPrototypeChain || !o.hasOwnProperty(p)) continue;
            if(typeof o[p] !== 'object') continue;
            if(o[p] === null || o[p] === undefined) continue;
            find(matches, o[p], prop, checkPrototypeChain);
        }
    }
    return function(o, prop, checkPrototypeChain){
        var matches = [];
        find(matches, o, prop, checkPrototypeChain);
        return matches;
    }
})();

然后,您可以基于此映射数组:

var userIds = someArray.map(function(e){ return find(e, 'user.id'); });

请注意,我要介绍原型链中可能存在的属性,但是在find函数中,我增加了在原型链中额外搜索属性的功能。

我假设您仅使用基元和对象/数组文字。 在这种情况下,以下方法(使用下划线)似乎可以解决问题。

var testSubject = {
    mykey: 9,
    firstArray: [
        {something: 9, another: {x: 'hello', mykey: 'dude'}, mykey: 'whatever'},
        {something: 9, another: {x: 'hello', mykey: 'dude2'}, mykey: 'whatever2'},
        {
            someArray: [
                {seven: 7, mykey: 'another'},
                {hasNo: 'mykey', atAll: 'mykey'}
            ]
        }
    ],
    anObject: {beef: 'jerky', mykey: 19}
};

function getValuesForKey(subject, searchKey) {
    return _.reduce(subject, function(memo, value, key) {
        if (_.isObject(value)) {
            memo = memo.concat(getValuesForKey(value, searchKey));
        } else if (key === searchKey) {
            memo.push(value);
        }
        return memo;
    }, []);
}

console.log(getValuesForKey(testSubject, 'mykey'));
// -> [9, "dude", "whatever", "dude2", "whatever2", "another", 19] 

它仅返回值列表,因为它们将共享相同的键(即指定的键)。 另外,我确实相信,如果任何匹配的键的值不是原始的,它们都将被忽略(例如,应忽略mykey: {…}mykey: […] )。 希望对您有所帮助。

暂无
暂无

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

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