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

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

本文关键字:数组 对象 格式 不知道 Javascript 获取 键值      更新时间:2023-09-26

假设我有一个类似对象数组的引用,例如array将是该数组的名称。现在我被要求创建一个数组,其中包含该数组中每个对象中的某些属性的所有值,例如"user.id"

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

是否有一个函数(jQuery,下划线等),可以创建这样一个数组?例: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: […]应该被忽略)。