简体   繁体   English

从现有数组和对象创建新对象

[英]Create new object from existing array and object

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 . 也就是说,如果obj包含名称为array[i]属性,则将该属性添加到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 . 如果您使用reduceforEachfor...of进行迭代,也许会更加清楚,那么索引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 . 它基本上仅根据array项来创建一个键接一个键的对象,其中每个键的值均取自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. 条件if (array[i] !== obj[i]) {试图用对象值而不是对象键检查数组键。 Also obj[i] is incorrect, since obj[0] does not exist with the key 0 . obj[i]也不正确,因为obj[0]与键0不存在。

This is another variation using Object.keys instead of for loop. 这是使用Object.keys代替for循环的另一种形式。

 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)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM