Search code examples
javascriptarraysjavascript-objects

Concatenating an array of nested objects


I tried to use the code below to concatenate multiple nested elements, and for some reason, undefined is showing up in my results.

arr = [
  {
    very_positive: ["It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.", "You may rely on it."]
  },
  {
    positive: ["As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes."]
  },
  {
    negative: ["Reply hazy, try again.", " Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again."]
  },
  {
    very_negative: ["Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful."]
  }
];

let flatArrObj = arr.map(list => `${list.very_positive} ${list.positive} ${list.negative} ${list.very_nagative}`)

Solution

  • Array.map() takes each element of the array and applies a function to it, for concatenation you could use reduce, or more simply

    arr = [{
        very_positive: ["It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.", "You may rely on it."]
      },
      {
        positive: ["As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes."]
      },
      {
        negative: ["Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again."]
      },
      {
        very_negative: ["Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful."]
      }
    ];
    
    let flatObj = [...arr[0].very_positive, ...arr[1].positive,  ...arr[2].negative,  ...arr[3].very_negative]
    
    console.log(flatObj);

    given your data structure.