Home > Blockchain >  How can I include an array into my JSON object in Javascript?
How can I include an array into my JSON object in Javascript?

Time:11-04

I'm trying to prepare an array into a json object to send to an API.

I'm struggling to figure out how to manipulate my array into the right shape.

My array looks something like this.

data: [
    ["Lisa", "Heinz", "1993-04-15" ],
    ["Bob", "Dylan", "1998-09-12"],
    ["Cabbage", "Man", "1990-01-11"],
    ["", "", ""]
  ]

I'd like it to be a json object looking like this:

{person:[{"name":"Lisa","last_name":"Heinz","dob":"1993-04-15"},{"name":"Bob","last_name":"Dylan","dob":"1998-09-12"},{"name":"Cabbage","last_name":"Man","dob":"1990-01-11"},{"name":"","last_name":"","dob":""}],"object_id":259,"test":"bob","attribute":"bob123"}

Currently I do this:

let json = {}
    for (let person of formData) {
        const identifier = `person${formData.indexOf(person)}`;
        json[identifier] = { 

name: person[0],
last_name: person[1],
dob: person[2]
                        }
                            } 
json.object_id = "259";
json.wp_test = "bob";
json.attribute = "bob123";

Which outputs something like this:

{"person0":{"name":"Lisa","last_name":"Heinz","dob":"1993-04-15"},"person1":{"name":"Bob","last_name":"Dylan","dob":"1998-09-12"},"person2":{"name":"Cabbage","last_name":"Man","dob":"1990-01-11"},"person3":{"name":"","last_name":"","dob":""},"object_id":259,"wp_test":"bob","attribute":"bob123"}

I've tried a variety of things to get the right shape - what's an easily understandable way to get there?

CodePudding user response:

It's just a matter of matching the correct keys/indexes.

var data = [
  ["Lisa", "Heinz", "1993-04-15"],
  ["Bob", "Dylan", "1998-09-12"],
  ["Cabbage", "Man", "1990-01-11"],
  ["", "", ""]
]

var persons = data.reduce(function(agg, item) {
  agg.push({
    name: item[0],
    last_name: item[1],
    dob: item[2],
  })
  return agg;
}, [])

var final = {
  person: persons,
  object_id: 259,
  wp_test: 'bob',
  attribute: 'bob123',
}

console.log(final)
.as-console-wrapper {max-height: 100% !important}

CodePudding user response:

You can simply achieve this by iterating the input array with the help of Array.map() method.

Live Demo :

const data = [
  ["Lisa", "Heinz", "1993-04-15" ],
  ["Bob", "Dylan", "1998-09-12"],
  ["Cabbage", "Man", "1990-01-11"],
  ["", "", ""]
];

const jsonObj = {};

jsonObj.person = data.map(arr => ({ name: arr[0], last_name: arr[1], dob: arr[2] }));

jsonObj.object_id = "259";
jsonObj.wp_test = "bob";
jsonObj.attribute = "bob123";

console.log(jsonObj);

  • Related