-1

I have an objects:

http ={" xxx": "#phone#","yyy": "1234", "zzz":5678 }

input= {"phone": "2", "id": "258 },

How do I find the #phone# value and replace it with 2 from input?

The #phone# key can be anything, not just "xxx".

MB12
  • 21
  • 2
  • You will have to iterate each key and replace them – Thum Choon Tat Mar 17 '21 at 10:37
  • 2
    Can you show the code which you have tried? – Hassan Imam Mar 17 '21 at 10:39
  • Loop over the object with `Object.entries`. Then, select the 2nd element(index of 1) of the subarray. Compare it with `#phone#`, if it true, then access the key by selecting the 1st element(index of 0) then `obj[WhateverKeyYouGot]` and replace with desired value – Akash Mar 17 '21 at 10:45
  • You can combine [Object.entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) with [Object.fromEntries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries). See: [example](https://jsfiddle.net/bgn6ht4e/) – Reyno Mar 17 '21 at 10:56

2 Answers2

0

You could use Object.entries() to iterate over each property of the object and then check with an if statement if the key-value is the one that you want and change it.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Camopy
  • 125
  • 1
  • 12
0

Use Object.entries() to loop over the properties of the object and then check with an if statement whether the value is the one that you want and change it to the desired value.

const entries = Object.entries(id);

entries.forEach((entry) => {
    if (entries[1] === '#phone#') {
        id[entry[0]] = 'SOME_VALUE';
    }
});

Akash
  • 762
  • 7
  • 25