【问题标题】:adding key to an object by looping goes error通过循环向对象添加键出错
【发布时间】:2021-03-30 15:30:33
【问题描述】:

我在通过循环向对象添加键时遇到问题 这是代码

function checkResult(want,reference)
{
  const keys = Object.keys(reference)
  for(let i=0;i<Object.keys(reference).length;i++){
    console.log(keys[i]+"ihn")
    if(keys[i] in want)
    {
      let temp1={}

      temp1.keys[i]=1
    }
  }
  return temp1
}

我在 temp1.keys[i]=1 处收到 错误 as TypeError: Cannot set property '0' of undefined

【问题讨论】:

  • 什么是wantreference 是什么?对象?字符串?
  • temp1[keys[i]] 应该这样做

标签: javascript node.js arrays json object


【解决方案1】:

const list = ["a", "b"]
console.log("List of what we want:")
console.log(list)

const obj = {
  "a": 0,
  "b": 0,
  "c": 0
}
console.log("Initial object:")
console.log(obj)

const checkResult = (want, reference) => {
  // creating a new temp objecct OUTSIDE of the for loop
  temp = {}
  
  // Array of the reference keys
  const keys = Object.keys(reference)

  // looping over keys in reference
  for (let i = 0; i < keys.length; i++) {
  
    // The current key
    const key = keys[i]
    
    // if the key is included in the 'want' list
    if (want.includes(key)) {

      // set a property in the temp object, but with a different value
      temp[key] = 1
    }
  }

  // when we are done, return the object
  return temp
}

const result = checkResult(list, obj)

console.log("Result:")
console.log(result)

【讨论】:

  • @ashwin-joshy,如果对您有帮助,请接受我的回答 :)
猜你喜欢
  • 1970-01-01
  • 2020-04-09
  • 1970-01-01
  • 2020-03-04
  • 1970-01-01
  • 2022-01-20
  • 2019-12-31
  • 1970-01-01
  • 2013-05-25
相关资源
最近更新 更多