Home > database >  How to This JSON from this Javascript array of arrays?
How to This JSON from this Javascript array of arrays?

Time:04-09

I'm asking this question again since I got downvotes due to unclear explanation in previous question:

I have this java script array of arrays

   arr1= [ 
       ['a', 'b'],
       ['1', '2']
       ]
           

And I need to form this JSON object

[
    {
        "label":"a",
        "value":"1"
    },
    {
        "label":"b",
        "value":"2"
    },
]
  

How do i do it?

CodePudding user response:

Using Array#map:

const arr = [ ['a', 'b'], ['1', '2'] ];

const [labels, values] = arr;
const res = labels.map((label, index) => ({ label, value: values[index] }));

console.log(res);

CodePudding user response:

You could take an array with the keys of the wanted objects and reduce and map the items.

const
    data = [['a', 'b'], ['1', '2']],
    keys = ['label', 'id'],
    result = data.reduce((r, a, i) => a.map((v, j) => ({ ...r[j], [keys[i]]: v })), []);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

Look at this ...

const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);

const obj = Object.fromEntries(entries);

console.log(obj);
// expected output: Object { foo: "bar", baz: 42 }

Did you mean something like this? Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries

  • Related