Ashwin Joshy
Ashwin Joshy

Reputation: 49

adding key to an object by looping goes error

I am having a trouble in adding a key to object by looping here's the code

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
}

here i am getting an error just at temp1.keys[i]=1 as TypeError: Cannot set property '0' of undefined

Upvotes: 1

Views: 34

Answers (1)

IvanD
IvanD

Reputation: 2933

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)

Upvotes: 2

Related Questions