从对象数组中获取键值数组,而不知道对象数组的格式(Javascript)
Get array of key-values from array of objects without knowing format of array of objects (Javascript)?
假设我有一个类似对象数组的引用,例如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: […]
应该被忽略)。
- 将数组对象传递到struts2中的操作类
- 如何使用jquery返回php-json数组对象
- 从其名称获取javascript数组对象
- 值未与数组对象绑定
- 如何按数组/对象值的倍数过滤对象数组
- 在表中显示数组对象
- 在数组对象中分组
- 将第二个或多个数组推送到数组对象 AngularJS 中
- 重新排列 JavaScript 数组/对象
- 键上的javascript数组对象过滤器
- handontable:在不更改数据数组/对象的情况下隐藏某些列
- 用于跟踪购物车可用性的Javascript数组/对象/哈希表
- 重建有角度的java脚本数组对象
- 对JSON数组对象进行排序
- 连接与数组对象相关的文本:方式和位置
- 哪些浏览器和版本支持将常见的类数组对象直接传递到fn.apply()
- 如何使用Handlebars循环数组对象和模板
- 是否可以引用JS数组/对象中的另一个元素
- Javascript中的名称索引-数组/对象
- 数组长度不等于数组对象