Home > database >  How to extract element from JSON array and put into another array
How to extract element from JSON array and put into another array

Time:12-15

How to convert this

[{"col":"ClientPolicy","st":"false","id":"1"},{"col":"Department","st":"true","id":"2"}]

to

[{"ClientPolicy":false,"Department":true}]

this in react js

CodePudding user response:

Use reduce function. Try like below.

const input = [{"col":"ClientPolicy","st":"false","id":"1"},{"col":"Department","st":"true","id":"2"}];

const output = input.reduce((prevValue, { col, st }) => {
    prevValue[col] = typeof st === "string" ? JSON.parse(st) : st
    return prevValue;
}, {});

console.log([output]);

CodePudding user response:

using Array.reduce

var array = [{
  "col": "ClientPolicy",
  "st": "false",
  "id": "1"
}, {
  "col": "Department",
  "st": "true",
  "id": "2"
}];

var cols = array.reduce((a, c) => {
  a[c.col] = Boolean(c.st);
  return a;
}, {});

var output = [];
output.push(cols);

console.log(output);

  • Related