开发者问题收集

将数组值添加为 JavaScript 对象属性

2021-03-13
90
function select(arr, obj) {
  var myKeys = Object.keys(obj);
  var myValues = Object.values(obj);
  var newObj = {};

  for(var i=0; i<myKeys.length; i++) {

    if(arr[i] === myKeys[i]) {
      newObj[myKeys[i]] = myValues[i];   
    }

  }
  
  return newObj;
}

var arr = ['a', 'c', 'e'];
var obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
};
var output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }

/*

If keys are present in the given array, but are not in 
the given object, it should ignore them.

It does not modify the passed in object.

*/

我无法将数组添加为对象属性。我创建了一个新对象来存储值,但它只存储了 arr[i] 的第一个实例。我现在很困惑,有什么可以帮到你吗?

3个回答

改为这样做

for(var i=0; i<arr.length; i++) {
    if(myKeys[arr[i]] !== undefined) {
        newObj[arr[i]] = myValues[i];   
    }
}

仅当匹配键的索引完全相同时,您的代码才有效。

Jkarttunen
2021-03-13

代码中的问题在于,它假定数组中的第 i 个值 必须 对应于对象的第 i 个键,但无法保证该顺序。

这是一个 函数式编程 风格的解决方案,它使用 Obect.fromEntries 来构造返回的对象:

const select = (arr, obj) =>
    Object.fromEntries(arr.filter(key => key in obj).map(key => [key, obj[key]]));

var arr = ['a', 'c', 'e'];
var obj = {a: 1,b: 2,c: 3,d: 4};
var output = select(arr, obj);
console.log(output);
trincot
2021-03-13

我将使用最近添加的 Object.fromEntries 直接从对象中过滤的一组键的映射中创建对象。

function select (arr, obj) {
   // get the keys from obj and filter to those present in arr
   var keys = Object.keys(obj).filter(key => arr.includes(key));
   // create an array of arrays where each inner array has a key and value
   var entries = keys.map(key => [key, obj[key]]);
   // call fromEntries with that new array.
   return Object.fromEntries(entries);
}

var arr = ['a', 'c', 'e'];
var obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
};
var output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }

/*

If keys are present in the given array, but are not in 
the given object, it should ignore them.

It does not modify the passed in object.

*/
Heretic Monkey
2021-03-13