:)我需要返回一个新对象,该对象的属性是给定对象中的属性,其键存在于给定数组中。
代码尝试:
var arr = ['a', 'c', 'e'];
var obj = {
a: 1,
b: 2,
c: 3,
d: 4
};
function select(arr, obj) {
var result = {};
var array = [];
for (var key in obj){
array.push(key);
}
var num = arr.length + obj.length;
for (var i = 0; i < num; i++) {
for(var j = 0; j < num; j++) {
if (arr[i] === array[j]) {
result.array[i] = obj.arr[i];
}
}
}
return result;
}
(不正确)结果:
{}
期望的结果:
// --> { a: 1, c: 3 }
有什么建议吗?谢谢! :)
答案 0 :(得分:2)
您可以迭代给定的键,测试它是否是对象中的键,并将值赋给结果对象中的相同键。
function select(arr, obj) {
var result = {};
arr.forEach(function (k) {
if (k in obj) {
result[k] = obj[k];
}
});
return result;
}
var arr = ['a', 'c', 'e'],
obj = { a: 1, b: 2, c: 3, d: 4 };
console.log(select(arr, obj));
答案 1 :(得分:2)
更长,但更易读的版本:
var arr = ['a', 'c', 'e'],
obj = {a:1,b:2,c:3,d:4},
hash = {};
arr.forEach(function(v){ //iterate over each element from arr
Object.keys(obj).some(function(c){ //check if any key from obj is equal to iterated element from arr
if (v == c) {
hash[v] = obj[c]; //if it is equal, make a new key inside hash obj and assign it's value from obj to it
}
});
});
console.log(hash);
简短版本:
var arr = ['a', 'c', 'e'],
obj = {a:1,b:2,c:3,d:4},
hash = {};
arr.forEach(v => Object.keys(obj).some(c => v == c ? hash[v] = obj[c] : null));
console.log(hash);