Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update every value of json array with dynamic key input (Javascript)

Input json

var foo = [
  { name: "John", age: "30", car: "yellow" },
  { name: "shayam", age: "13", car: "blue" },
  { name: "ram", age: "23", car: "red" },
];
function poo(keyName, value) {
   // Change all the value of JSON array according to key and value
}
poo("car", "orange"); 
poo("age","20");

expected output: 1

[
  { name: "John", age: 30, car: "orange" },
  { name: "shayam", age: 13, car: "orange" },
  { name: "ram", age: "23", car: "orange" }
]

expected output: 2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    { name: "John", age: "20", car: "orange" },
    { name: "shayam", age: "20", car: "orange" },
    { name: "ram", age: "20", car: "orange" }
];

>Solution :

The main key here is using dynamic object key with bracket notation, and use forEach and modify the target object without need to make a copy of it.

var foo = [   { name: "John", age: "30", car: "yellow" },   { name: "shayam", age: "13", car: "blue" },   { name: "ram", age: "23", car: "red" }, ];

const poo = (key, value) => {
  foo.forEach(i => i[key] = value)
  return foo
}

console.log(poo('car', 'orange'));
console.log(poo('age', '20'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading