我想从这里得到:
例如= {[ 名称:someone1 城市:somewhere1 状态:someplace1},{ 名称:someone2 城市:somewhere2 状态:someplace2}]在这里:
example.name = [someone1,someone2]在短短一个code越好。很显然,我可以只循环,并建立数组,但我需要这个做各种不同的物体了大量的时间。我可以写一个函数来做到这一点,但是这将是很难使一般功能足够我的应用程序。
有jQuery的这个快捷方式?
解决方案您可以通过对象键循环,并使用推:
\r\r
例如= {[\r 名称:someone1\r 城市:somewhere1\r 状态:someplace1\r},{\r 名称:someone2\r 城市:somewhere2\r 状态:someplace2\r}];\r变种arrNames = [];\r//通过对象键循环\rObject.keys(例如).forEach(功能(键){\r //获取名称的值\r VAR VAL =例如[关键] [名称];\r //推名称字符串数组中\r arrNames.push(VAL);\r});\r的console.log(arrNames); //输出[someone1,someone2]\r\r\r
在@Felix建议(与我同意)有没有必要使用 Object.keys :
\r\r
例如= {[\r 名称:someone1\r 城市:somewhere1\r 状态:someplace1\r},{\r 名称:someone2\r 城市:somewhere2\r 状态:someplace2\r}];\r变种arrNames = [];\r//通过对象键循环\rexample.forEach(函数(项目){\r //获取名称的值\r VAR VAL = item.name\r //推名称字符串数组中\r arrNames.push(VAL);\r});\r的console.log(arrNames); //输出[someone1,someone2]\r\r\r
参考
Object.keys()
Array.prototype.forEach()
Array.prototype.push()
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
Object.keys()
Array.prototype.forEach()
Array.prototype.push()
更多推荐
获取属性值从数组使用jQuery对象数组
发布评论