0

I am looking to map one of my response objects to the existing array of objects by running two different loops, somehow I am not able to remove the value if the matched key is not found in the object.

Is there any way I can make the value null if the keys don't match?

I tried following:

const data = {
  test1: 1,
  test2: 2
};

const val = [
  {
    id: 'test1',
    val: 2222
  },
  {
    id: 'test2',
    val: 5555
  },
  {
    id: 'test3',
    val: 4444
  }
];

val.forEach(element => {
  Object.entries(data).forEach(([key, value]) => {
    if (element.id === key) {
      element.val = value;
    }
  });
});

console.log(val);
// output:
// const val = [
//   {
//     id: 'test1',
//     val: 1
//   },
//   {
//     id: 'test2',
//     val: 2
//   },
//   {
//     id: 'test3',
//     val: ""
//   }
// ];

1 Answer 1

1

You don't need a loop. Just check if the property exists.

const data = {
  test1: 1,
  test2: 2
};

const val = [{
    id: 'test1',
    val: 2222
  },
  {
    id: 'test2',
    val: 5555
  },
  {
    id: 'test3',
    val: 4444
  }
];

val.forEach(element => {
  if (data.hasOwnProperty(element.id)) {
    element.val = data[element.id];
  } else {
    element.val = "";
  }
});

console.log(val);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.