我想从这里开始:
example = [{
name: "someone1",
city: "somewhere1",
state: "someplace1"
},{
name: "someone2",
city: "somewhere2",
state: "someplace2"
}]
到这里:
example.name = [ "someone1", "someone2" ]
尽可能少的代码。显然我可以循环它并构建数组但我需要在各种对象上执行此操作很多次。我可以编写一个函数来完成它,但是很难使函数对我的应用程序来说足够通用。
jQuery中有这个快捷方式吗?
答案 0 :(得分:8)
您可以使用name
遍历对象键并将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"]

在@Felix建议之后(我同意),无需使用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"]

<强>参考强>
答案 1 :(得分:6)
答案 2 :(得分:6)
我在这里为你做了一个快速测试:http://jsperf.com/jquery-vs-javascriptlvjsklvjsfklsfklsdjfk
它由三个解决方案组成:
循环的基本
for (var i = 0; i < example.length; i++) {
array.push(example[i].name);
}
jQuery $ .each()
$.each(example, function(i, item) {
array.push(example[i].name);
});
一个答案贴在这个帖子上
Object.keys(example).forEach(function(key) {
//get the value of name
var val = example[key]["name"];
//push the name string in the array
array.push(val);
});
以下是结果(更大的条形更好)
基本上你必须要记住的是,jQuery可能有一个快捷方式,包含更少的代码和#34;但实际上它会比你自己编写代码的性能更差。
答案 3 :(得分:2)
以下是使用jinqJs
的方法代码行是:
jinqJs().from(example).select(function(row){return row.name;});
var example = [{
name: "someone1",
city: "somewhere1",
state: "someplace1"
},{
name: "someone2",
city: "somewhere2",
state: "someplace2"
}];
var result = jinqJs().from(example).select(function(row){return row.name;});
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 2) + '</pre><br><br>';
&#13;
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.min.js"></script>
&#13;
答案 4 :(得分:1)
这是我能想到的最简单的解决方案:
function doThat (myArray) {
newObject = {};
myArray.forEach(function (obj, idx) {
var keys = Object.keys(obj);
keys.forEach(function (key) {
if (!obj[key]) {
newObject[key] = [];
}
newObject[key][idx] = obj[key];
});
});
return newObject;
}