I'm trying to return a new object with properties given in the existing object and keys present in a given array. I can't mutate the object and if the keys are present in the array but not in the object the key should be ignored. I get hung up on how to compare the array elements to the objects keys.
function picker(array, obj) {
var newObj = {};
for (var i = 0; i < arrary.length; i++) {
if (array[i] !== obj[i]) {
newObj[array[i]] = obj[i];
}
}
return newObj;
}
var array = [
'a',
'c',
'e'
];
var obj = {
a: 1,
b: 2,
c: 3,
d: 4
};
var bubble = picker(array, obj);
console.log(bubble); result --> `{ a: 1, c: 3 }`
You probably meant something like this:
function picker(array, obj) { var newObj = {}; for (var i = 0; i < array.length; i++) { if (array[i] in obj) { newObj[array[i]] = obj[array[i]]; } } return newObj; } var array = ['a', 'c', 'e']; var obj = {a: 1, b: 2, c: 3, d: 4}; console.log(picker(array, obj));
That is, if obj
contains the property with name array[i]
, then add that property to newObj
.
Maybe it will be clearer if you iterate with reduce
, forEach
or for...of
, then you won't be confused by the index i
.
function picker(array, obj) { return array.reduce(function(newObj, key) { if (key in obj) newObj[key] = obj[key]; return newObj; }, {}); } var array = ['a', 'c', 'e']; var obj = {a: 1, b: 2, c: 3, d: 4}; console.log(picker(array, obj));
You could do something like
const x = array.reduce((total, current) => current in obj ? ({
...total,
[current]: obj[current]
}) : total, {});
Which basically creates an object, key after key, based only on items of the array
, where the value per key is taken from obj
. Check out the fiddle .
You haven't checked whether the key is existing in the array.
The condition if (array[i] !== obj[i]) {
is trying to check the array key with object value instead of object key. Also obj[i]
is incorrect, since obj[0]
does not exist with the key 0
.
This is another variation using Object.keys
instead of for
loop.
function picker(array, obj) { var newObj = {}; Object.keys(obj).forEach(function(key){ if(array.indexOf(key) > -1) { newObj[key] = obj[key]; } }); return newObj; } var array = ['a', 'c', 'e']; var obj = {a: 1, b: 2, c: 3, d: 4}; console.log(picker(array, obj));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.