Search code examples
javascriptarrayslodash

Add key/value pair to object within array of arrays?


Given the following structure:

const data = {
  "show": "Family Guy",
  "characters": [
      [{name: 'Peter', age: 40, city: 'Quahog'}],
      [{name: 'Louis', age: 30}],
      [{name: 'Chris', age: 16}],
      [{name: 'Stewie', age: 1}]
    ]
 }

How can we add to each character the key/value pair of city: 'Quahog' so the output looks as follows:

const item = {
  "show": "Family Guy",
  "characters": [
      [{name: 'Peter', age: 40, city: 'Quahog'}],
      [{name: 'Louis', age: 30, city: 'Quahog'}], // city added
      [{name: 'Chris', age: 16, city: 'Quahog'}], // city added
      [{name: 'Stewie', age: 1, city: 'Quahog'}]  // city added
    ]
 }

We tried using:

let city = data.characters.[0][0].city;
costs = _.map(items, (itemArray) => {
            items = _.map(itemArray, (item) => {
              if(!item.city) {
                item.city = city;
              }
        });

But it's not working as intended and we can't get the desired output. Any idea how to accomplish this?


Solution

  • Here is another way of doing it with .reduce():

    const data = {
      "show": "Family Guy",
      "characters": [
      [{name: 'Peter', age: 40, city: 'Quahog'}],
      [{name: 'Louis', age: 30}],
      [{name: 'Chris', age: 16}],
      [{name: 'Stewie', age: 1}]
    ]
     };
    
    data.characters.reduce((a,c)=>
     (c[0].city=a[0].city,a));
    
    console.log(data);

    When using .reduce() without a second argument it will pick up the first array element as the initial value which is then used as a template to copy the .city property to all the other elements. The actual return value of the .reduce() method is discarded but the input array itself (data) is modified in the process and is then shown in the console.log() expression.