1
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] 的第一个实例。我现在很困惑,有什么帮助吗?

4

3 回答 3

2

改为这样做

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

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

于 2021-03-13T21:19:18.920 回答
1

您的代码中的问题是它假定数组中的第 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);

于 2021-03-13T21:38:04.390 回答
0

我将使用相对最近添加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.

*/

于 2021-03-13T21:35:06.063 回答