1

Input js Array

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"); // 1
poo("age","20");     // 2

expected output 1

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

expected output 2

  [ { name: "John",   age: "20", car: "orange" } 
  , { name: "shayam", age: "20", car: "orange" } 
  , { name: "ram",    age: "20", car: "orange" } 
  ] 
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40

3 Answers3

0
function poo(keyName, value) {
  foo.forEach(it => {
    it[keyName] = value
  })
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
spyhere
  • 54
  • 3
  • If you're modifying the objects in place, there's no need to create a new array with `map`. – Barmar Nov 16 '22 at 17:47
0

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'));
Mina
  • 14,386
  • 3
  • 13
  • 26
  • better to write `foo.forEach(row => row[key] = value)`, -> by convention the letter `i` represents a numeric index. – Mister Jojo Nov 16 '22 at 18:09
0
function poo(keyName, value) {
    data = data.map((v) =>{
        v[keyName] = value;
        return v;
    })
}
Nishanth
  • 304
  • 3
  • 12
  • If you're modifying the objects in place, there's no need to create a new array with `map()`. – Barmar Nov 16 '22 at 20:03