Christian
Christian

Reputation: 63

How to create a new json row by combining elements from multiple other json rows dynamically

I have json data in fields that are split across rows. I want to have all these fields in a single row. I would like to write a javascript function that takes the original input and produces the output. I am very new to javascript. I would like to do this in a dynamic way so that I don't have to explicitly name the new fields -- rather iterate through all the fields in each row one by one and append them to a new row, with the same names/values. Thanks in advance.

Starting json:

[
    {
        "name": "Sara Smith",
        "dob": "19831002"
    },
    {
        "title": "director",
        "emails": [
            "[email protected]",
            "[email protected]"
        ]
    },
    {
        "phones": [
            {
                "type": "home",
                "number": "3452345432"
            },
            {
                "type": "work",
                "number": "3452345343"
            }
        ]
    }
]   

Desired end state json:

[
    {
        "name": "Sara Smith",
        "dob": "19831002"
        "title": "director",
        "emails": [
            "[email protected]",
            "[email protected]"
        ]
        "phones": [
            {
                "type": "home",
                "number": "3452345432"
            },
            {
                "type": "work",
                "number": "3452345343"
            }
        ]
    }
]       

Upvotes: 0

Views: 133

Answers (2)

Shidersz
Shidersz

Reputation: 17190

One possible solution is to use Array.reduce() in combination with Object.assign():

const input = [
  {"name": "Sara Smith", "dob": "19831002"},
  {
    "title": "director",
    "emails": ["[email protected]", "[email protected]"]
  },
  {
    "phones": [
      {"type": "home", "number": "3452345432"},
      {"type": "work", "number": "3452345343"}
    ]
  }
];

let output = input.reduce((acc, curr) =>
{
    Object.assign(acc[0], curr);
    return acc;
}, [{}]);

console.log(output);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44125

Use reduce:

const startJSON = [{
    "name": "Sara Smith",
    "dob": "19831002"
  },
  {
    "title": "director",
    "emails": [
      "[email protected]",
      "[email protected]"
    ]
  },
  {
    "phones": [{
        "type": "home",
        "number": "3452345432"
      },
      {
        "type": "work",
        "number": "3452345343"
      }
    ]
  }
];

const endJSON = [startJSON.reduce((acc, curr) => ({ ...acc, ...curr }))];

console.log(endJSON);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Upvotes: 1

Related Questions