-3

I have JSON like

 0:{columnName:"gender",seedValues:["M","F"]}
 1:{columnName:"entity_type",seedValues:["O","I"]}

I want JSON like

{
  "gender":["M","F"],
  "entity_type":["O","I"]
 }

I have tried

let value = this.values;
for(let i in value) {
    if(value[i].columnName=='gender')
    {
        this.gender.push(value[i].seedValues);
    }
    if(value[i].columnName=='entity_type')
    {
        this.entity.push(value[i].seedValues);
    }
    let obj = {
        "gender":this.gender,
        "entity_type":this.entity
    }
}

In Angular 6 or JavaScript, But I want my JSON structure like this

{
  "gender":["M","F"],
  "entity_type":["O","I"]
}
YakovL
  • 7,557
  • 12
  • 62
  • 102
  • 1
    JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Jun 24 '19 at 08:56
  • 1
    Possible duplicate of [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Liam Jun 24 '19 at 08:56

1 Answers1

0

Firstly, that's not JSON, that's pure JS. Secondly, you can use reduce:

const arr = [{columnName:"gender",seedValues:["M","F"]},{columnName:"entity_type",seedValues:["O","I"]}];
const res = arr.reduce((a, { columnName, seedValues }) => (a[columnName] = seedValues, a), {});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Or, you could make each item in the array its own object based on the key/value, then reduce those together:

const arr = [{columnName:"gender",seedValues:["M","F"]},{columnName:"entity_type",seedValues:["O","I"]}];
const res = arr.map(({ columnName, seedValues }) => ({ [columnName]: seedValues })).reduce((a, c) => ({ ...a, ...c }));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79