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

时间:2021-03-13 21:14:12

标签: javascript

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 个答案:

答案 0 :(得分:2)

改为这样做

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

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

答案 1 :(得分:1)

您代码中的问题是它假定数组中的第 ith必须对应于数组的第 ith 键对象,但不保证该顺序。

这是一个函数式编程风格的解决方案,它使用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);

答案 2 :(得分:0)

不能保证 arr 中的项目在 index 中具有相同的 obj

所以在您的情况下,arr[0]myKeys[0] 都是 'a',这就是它通过的原因。但是 arr[1]='c'myKeys[1]='b'(不是 'c')。

这是一个可能的修复:

  1. 使用 arr 迭代 for-loop 的元素,并在每次迭代中检查 obj 是否具有此 key
  2. 如果是,则将此记录添加到 newObj

function select (arr, obj) {
  const myKeys = Object.keys(obj);
  const newObj = {};
  for(let i = 0; i < arr.length; i++) {
    const currentKey = arr[i];
    if(obj[currentKey]) {
      newObj[currentKey] = obj[currentKey];   
    }
  }
  return newObj;
}

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

另一种可能的解决方案:

  1. 使用 .reduce 迭代 arr 的元素
  2. 在每次迭代中,如果此key也在obj中,则将记录添加到newObj以最终返回

function select (arr, obj) {
  return arr.reduce((newObj, currentKey) => {
    if(obj[currentKey]) {
      newObj[currentKey] = obj[currentKey];   
    }
    return newObj;
  }, {});
}

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

答案 3 :(得分: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.

*/