我需要创建一个迭代对象数组的新对象,最初看起来像这样:
startObj = [{'prop': true}, {'prop': false}];
我希望结果是:
endObj = {0: true, 1: false}
我在考虑使用$.each
,但后来我不知道如何从这里开始。任何提示?
$.each([{'prop': true}, {'prop': false}], function (i, o) {
var newObj;
// the new object should look like this
// newObj = {0: true, 1: false}
});
答案 0 :(得分:12)
这是一个单行。
var newObj = $.map(oldObj, function(val) { return val.prop; });
如果OP真的想要一个对象(或者更确切地说,不想要一个数组)......
var newObj = $.extend({}, $.map(oldObj, function(val) { return val.prop; }));
答案 1 :(得分:7)
var newObj = {};
$.each([{'prop': true}, {'prop': false}], function (i, o) {
newObj[i] = o.prop;
});
答案 2 :(得分:1)
首先,这只是本机JS,这里不需要jQuery。
var startObj = [{'prop': true}, {'prop': false}],
endObj = [], // This could also be {} if you want but if you just have an array in startObj, it doesn't make much sense
i = 0,
i_max = startObj.length;
for (i; i < i_max; i++) {
endObj.push( startObj[i].prop );
// if you changed endObj to be {} then use the following line instead of the one above
// endObj[i] = startObj[i].prop;
}
答案 3 :(得分:0)
你真的不是在这里创建一个对象,而是一个数组:
var newObj = [];//array
$.each([{'prop': true}, {'prop': false}], function (i, o)
{
newObj[i] = o.prop
});
但是为了避免使用全局变量,你可能想要使用IIFE:
var newObj = (function()
{//takes any amount of objects as argument
var returnArray = [];
var argumentsToArray = Array.prototype.slice.apply(arguments,[0]);//create array of objects passed
$.each(argumentsToArray, function (i, o)
{
returnArray[i] = o.prop
});
return returnArray;//is assigned to newObj
})({'prop': true}, {'prop': false});//1 obj, 2, 3, 4, 5... doesn't matter
答案 4 :(得分:-3)
var obj = "{";
$.each([{'prop': true}, {'prop': false}], function (index, o) {
obj += '"' + index + '":' + o.prop + ",";
});
var newObj = obj.substring(0, obj.length - 1);
newObj += "}";
console.log(newObj);
console.log($.parseJSON(newObj));