获取属性值从数组使用jQuery对象数组 [英] Get array of property values from array of objects with jquery
问题描述
我想从这里得到:
例如= {[
名称:someone1
城市:somewhere1
状态:someplace1
},{
名称:someone2
城市:somewhere2
状态:someplace2
}]
在这里:
example.name = [someone1,someone2]
在短短一个code越好。很显然,我可以只循环,并建立数组,但我需要这个做各种不同的物体了大量的时间。我可以写一个函数来做到这一点,但是这将是很难使一般功能足够我的应用程序。
有jQuery的这个快捷方式?
您可以通过对象键循环,并使用名称
>推:
例如= {[\r
名称:someone1\r
城市:somewhere1\r
状态:someplace1\r
},{\r
名称:someone2\r
城市:somewhere2\r
状态:someplace2\r
}];\r
变种arrNames = [];\r
//通过对象键循环\r
Object.keys(例如).forEach(功能(键){\r
//获取名称的值\r
VAR VAL =例如[关键] [名称];\r
//推名称字符串数组中\r
arrNames.push(VAL);\r
});\r
的console.log(arrNames); //输出[someone1,someone2]
\r
在@Felix建议(与我同意)有没有必要使用 Object.keys
:
例如= {[\r
名称:someone1\r
城市:somewhere1\r
状态:someplace1\r
},{\r
名称:someone2\r
城市:somewhere2\r
状态:someplace2\r
}];\r
变种arrNames = [];\r
//通过对象键循环\r
example.forEach(函数(项目){\r
//获取名称的值\r
VAR VAL = item.name\r
//推名称字符串数组中\r
arrNames.push(VAL);\r
});\r
的console.log(arrNames); //输出[someone1,someone2]
\r
参考
<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\"相对=nofollow> Array.prototype.forEach()
I am trying to get from here:
example = [{
name: "someone1",
city: "somewhere1",
state: "someplace1"
},{
name: "someone2",
city: "somewhere2",
state: "someplace2"
}]
to here:
example.name = [ "someone1", "someone2" ]
In as little a code as possible. Obviously I could just loop it and build the array but I need to do this a large number of times on a variety of objects. I could write a function to do it but it would be difficult to make the function general enough for my application.
Is there a shortcut for this in jQuery?
You can iterate through the object keys and save the name
in the array using push
:
example = [{
name: "someone1",
city: "somewhere1",
state: "someplace1"
}, {
name: "someone2",
city: "somewhere2",
state: "someplace2"
}];
var arrNames = [];
//iterate through object keys
Object.keys(example).forEach(function(key) {
//get the value of name
var val = example[key]["name"];
//push the name string in the array
arrNames.push(val);
});
console.log(arrNames);//prints ["someone1", "someone2"]
After @Felix suggestion(with which I agree) there is no need to use Object.keys
:
example = [{
name: "someone1",
city: "somewhere1",
state: "someplace1"
}, {
name: "someone2",
city: "somewhere2",
state: "someplace2"
}];
var arrNames = [];
//iterate through object keys
example.forEach(function(item) {
//get the value of name
var val = item.name
//push the name string in the array
arrNames.push(val);
});
console.log(arrNames); //prints ["someone1", "someone2"]
References
这篇关于获取属性值从数组使用jQuery对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!