我有一个相当基本的JavaScript问题,我似乎无法弄清楚。假设我有一个这样的数据对象:
var data = [
{
key: 1,
attr2: "2",
attr3: "3",
attr4: "4",
attr5: "5"
};
{
key: 2,
attr2: "10",
attr3: "3a",
attr4: "ad",
attr5: "5asdf"
};
{
key: 3,
attr2: "a",
attr3: "b",
attr4: "c",
attr5: "d"
};
我想用attr1和attr2创建另一个对象,我这样做吗?
var data2 = data[attr1, attr2]
以这种方式尝试,但我得到了attr1 is undefined
。
答案 0 :(得分:1)
使用Array#map
方法使用data
数组元素生成新数组。
var res = data.map(function(o) {
return {
attr1: o.attr1,
attr2: o.attr2
}
})
var data = [{
key: 1,
attr2: 2,
attr3: 3,
attr4: 4,
attr5: 5
}, {
key: 2,
attr2: 10,
attr3: '3a',
attr4: 'ad',
attr5: '5asdf'
}, {
key: 3,
attr2: 'a',
attr3: 'b',
attr4: 'c',
attr5: 'd'
}];
var res = data.map(function(o) {
return {
attr1: o.attr1,
attr2: o.attr2
}
})
console.log(res);

更新1:使用ES6 arrow function和destructuring assignment。
var res = data.map(({attr1, attr2}) => ({attr1, attr2}))
var data = [{
key: 1,
attr2: 2,
attr3: 3,
attr4: 4,
attr5: 5
}, {
key: 2,
attr2: 10,
attr3: '3a',
attr4: 'ad',
attr5: '5asdf'
}, {
key: 3,
attr2: 'a',
attr3: 'b',
attr4: 'c',
attr5: 'd'
}];
var res = data.map(({attr1, attr2}) => ({attr1, attr2}))
console.log(res);

更新2:如果要从对象获取多个属性并将键存储在数组中,请使用Array#reduce
方法生成对象。
var res = data.map(function(obj) {
return keysArray.reduce(function(o, k) { // generate object
o[k] = obj[k]; // define the property
return o; // return object reference
}, {}); // set iinitial value as empty object
});
var data = [{
key: 1,
attr2: 2,
attr3: 3,
attr4: 4,
attr5: 5
}, {
key: 2,
attr2: 10,
attr3: '3a',
attr4: 'ad',
attr5: '5asdf'
}, {
key: 3,
attr2: 'a',
attr3: 'b',
attr4: 'c',
attr5: 'd'
}],
keys = ['attr1', 'attr2'];
var res = data.map(function(obj) {
return keys.reduce(function(o, k) {
o[k] = obj[k];
return o;
}, {});
});
console.log(res);

答案 1 :(得分:1)
您可以使用带有键的数组,并使用所需的键映射新对象。
虽然没有密钥attr1
,但未定义。
var data = [{ key: 1, attr2: 2, attr3: 3, attr4: 4, attr5: 5 }, { key: 2, attr2: 10, attr3: '3a', attr4: 'ad', attr5: '5asdf' }, { key: 3, attr2: 'a', attr3: 'b', attr4: 'c', attr5: 'd' }],
keys = ['attr1', 'attr2'],
result = data.map(function (a) {
var o = {};
keys.forEach(function (k) {
o[k] = a[k];
});
return o;
});
console.log(result);

额外奖励:ES6中包含Array#reduce
和Object.assign
的简短版本。
var data = [{ key: 1, attr2: 2, attr3: 3, attr4: 4, attr5: 5 }, { key: 2, attr2: 10, attr3: '3a', attr4: 'ad', attr5: '5asdf' }, { key: 3, attr2: 'a', attr3: 'b', attr4: 'c', attr5: 'd' }],
keys = ['attr1', 'attr2'],
result = data.map(o => keys.reduce((r, k) => Object.assign(r, { [k]: o[k] }), {}));
console.log(result);