Reputation: 83
:) I need to return a new object whose properties are those in the given object and whose keys are present in the given array.
code attempt:
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;
}
(incorrect) result:
{}
desired result:
// --> { a: 1, c: 3 }
Any advice? Thank you! :)
Upvotes: 1
Views: 766
Reputation: 41893
Longer, but more readable version:
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);
Short version:
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);
Upvotes: 2
Reputation: 386560
You could iterate the given keys, test if it is a key in the object and assign the value to the same key in the result object.
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));
Upvotes: 2