3

What is the Best way to convert,

{
   "columns":[
      "name",
      "color"
   ],
   "values":[
      [
         "lion",
         "yellow"
      ],
      [
         "crow",
         "black"
      ]
   ]
}

into

{
   "data":[
      {
        "name":"lion",
        "color":"yellow"
      },
      {
         "name":"crow",
         "color":"black"
      }
   ]
}

Rather than loop, Is there any function available ? Can I achieved it through something like extend() ?

0

3 Answers 3

4

You could use Object.assign with spread syntax ... for the parts.

var object = { columns: ["name", "color"], values: [["lion", "yellow"], ["crow", "black"]] },
    result = { data: object.values.map(v => Object.assign(...object.columns.map((c, i) => ({[c]: v[i]})))) };

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

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

Comments

2

You can do do it with combination of map and reduce. Reducing original columns array will allow to code to work with any number of columns, it will pick up corresponding value by index:

const result = {data: data.values.map(el => {
  return data.columns.reduce((prev, curr, index) => {
    prev[curr] = el[index]
    return prev
  }, {})
})}

Check the demo below.

const data = {
   "columns":[
      "name",
      "color"
   ],
   "values":[
      [
         "lion",
         "yellow"
      ],
      [
         "crow",
         "black"
      ]
   ]
}

const result = {data: data.values.map(el => {
  return data.columns.reduce((prev, curr, index) => {
    prev[curr] = el[index]
    return prev
  }, {})
})}

console.log(result)

Comments

2

You can get vales of .columns array using destructuring assignment, spread element; for..of loop to assign computed properties of .columns array as strings as properties of objects at data array by iterating .values property of original object, assign value of each array as value of created object

let obj = {
   "columns":[
      "name",
      "color"
   ],
   "values":[
      [
         "lion",
         "yellow"
      ],
      [
         "crow",
         "black"
      ]
   ]
}

let [res, key, value] = [{data:Array()}, ...obj.columns];

for (let [a, b] of [...obj.values]) res.data.push({[key]:a, [value]:b});

console.log(res);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.