Home > Mobile >  array of object to json javascript
array of object to json javascript

Time:01-14

I have an array of object like this

{
  "division": "IT",
   "id": "0002",
  "gender": [
    "mr.",
    "mr."
  ],
  "full_name": [
    "John Doe",
    "John Doe"
  ],
  "address": [
    "New York",
    "New York"
  ]
}

i need to make json like this using javascript.

  {
  "data": {
    "divisions": "IT",
    "id": "0002",
    "data": [
      {
        "gender": "mr.",
        "full_name": "John Doe",
        "address": "New York"
      },
      {
        "gender": "mr.",
        "full_name": "Steve Doe",
        "address": "New York"
      }
    ]
  }
}

is this possible using js or jquery?
i've searching about it and try different method but the result far from my expectations.
i appreciate any answer. thank you

CodePudding user response:

main is your default variable.

  {
       "data" : {
       "division": main.division,
       "id": main.id,
       "data": main.gender.map((gender, index) => ({
         "gender": gender,
         "full_name": main.full_name[index],
         "address": main.address[index],
       }))
  }

CodePudding user response:

You could tranform arrays to data objects take all others as properties.

const
    source = { division: "IT", id: "0002", gender: ["mr.", "mr."], full_name: ["John Doe", "John Doe"], address: ["New York", "New York"] },
    target = Object
        .entries(source)
        .reduce((r, [k, v]) => {
            if (Array.isArray(v)) {
                r.data = v.reduce((q, s, i) => {
                    (q[i] ??= {})[k] = s;
                    return q;
                }, r.data || []);
            } else {
                r[k] = v;
            }
            return r;
        }, {});

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

CodePudding user response:

You're essentially needing to zip together 3 arrays, which you can write a method to help you with:

const zip = (fun, first, ...rest) => {
   if(!rest.every(x => x.length == first.length))
    throw "all arrays must be same length";
   
   return first.map( 
     (e,i) =>  fun([e,...rest.map(x => x[i])])
   );
}

Given that method, your code is fairly simple:

const zip = (fun, first, ...rest) => {
   if(!rest.every(x => x.length == first.length))
    throw "all arrays must be same length";
   
   return first.map( 
     (e,i) =>  fun([e,...rest.map(x => x[i])])
   );
}

const input = {"division":"IT","id":"0002","gender":["mr.","mr."],"full_name":["John Doe","John Doe"],"address":["New York","New York"]};


const result = {
  data: {
    division: input.division,
    id: input.id,
    data: zip( 
      ([gender, full_name, address]) => ({gender,full_name,address}), 
      input.gender,
      input.full_name, 
      input.address
    )
  }
}

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

  •  Tags:  
  • Related