2

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

2 Answers 2

2

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]);

Sign up to request clarification or add additional context in comments.

5 Comments

@sudesh sampath, check this out !!
Thank you, Can you suggest how to get output as this, (true false should be in boolean format. [ { "ClientPolicy": false , "Department": true } ]
@sudeshsampath, I have updated the answer with boolean values !! Can you please mark this as the answer once you validated? Thanks!
boolean conversion is ok now, little more thing to do, the final output should be like this [ { "ClientPolicy": false , "Department": true } ] only one {} is required, can you suggest me Please
@sudeshsampath, updated the answer
1

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);

1 Comment

this is also correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.