Search code examples
javascriptarraysobjectconcatenation

Join values within multiple objects


I got the below object data which I need to join together, how can I achieve the output below provided that "foo" and "bar" would always have the same child elements.

{
  "foo": {
    "aaa": 1,
    "bbb": 2,
    "ccc": 3,
  },
  "bar:" {
    "aaa": "One",
    "bbb": "Two",
    "ccc": "Three",
  }
}

Expected output to be

<li>1 One</li>
<li>2 Two</li>
<li>3 Three</li>

Solution

  • Try this

    var foobar = {
      "foo": {
        "aaa": 1,
        "bbb": 2,
        "ccc": 3
      },
      "bar": {
        "aaa": "One",
        "bbb": "Two",
        "ccc": "Three"
      }
    };
    
    let mappedArray = Object.keys(foobar.bar).map(xxx=> "<li>" + foobar.foo[xxx] + " " + foobar.bar[xxx] + "</li>");
    console.log(mappedArray.join("\n"));