The question itself is probably in need of editing but hear me out pls. I have this:
[
["a","b","c"],
["apple", "orange", "banana"],
["kiwi", "tomato", "avocado"],
["beans", "asparagus", "spinach"]
]
I need it so that it will look like the one below:
[
{"a":"apple", "b":"orange", "c":"banana"},
{"a":"kiwi", "b":"tomato", "c":"avocado"},
{"a":"a", "b":"asparagus", "c":"spinach"}
]
I have done something like this:
const rows = [
["a","b","c"],
["apple", "orange", "banana"],
["kiwi", "tomato", "avocado"],
["beans", "asparagus", "spinach"]
]
const dataObj = {};
const dataArr = [];
if (rows.length) {
keys = rows[0];
values = rows[0];
rows.forEach((element, i) => {
values = rows[i];
keys.forEach((key, j) => {
dataObj[key] = values[j];
dataArr.push(dataObj);
});
});
}
To no avail and got something like this:
[
{"a":"apple", "b":"orange", "c":"banana"},
{"a":"apple", "b":"orange", "c":"banana"},
{"a":"apple", "b":"orange", "c":"banana"}
]
This is not the desired output. If you can help me out - and our community! - it would be super. Thanks!
You can use couple of Array functions to achieve this:
Array.shift
: To pick the first element and remove it from arrayArray.map
: To transform items into objectconst rows = [
["a", "b", "c"],
["apple", "orange", "banana"],
["kiwi", "tomato", "avocado"],
["beans", "asparagus", "spinach"]
]
const keys = rows.shift();
const map = rows.map((item) => {
const obj = {}
keys.forEach((key, index) => {
obj[key] = item[index]
})
return obj
})
console.log(map)
If you can use lodash
:
Check it out in this sandbox
import _ from 'lodash';
const input = [
["a","b","c"],
["apple", "orange", "banana"],
["kiwi", "tomato", "avocado"],
["beans", "asparagus", "spinach"]
]
const keys = input[0];
const values = input.splice(1);
console.log(keys);
console.log(values);
const output = values.map(row => _.zipObject(keys, row));
console.log(output);
/*
[
{"a":"apple","b":"orange","c":"banana"},
{"a":"kiwi","b":"tomato","c":"avocado"},
{"a":"beans","b":"asparagus","c":"spinach"}
]
*/
Modified your code a little bit for the solution
const rows = [
["a","b","c"],
["apple", "orange", "banana"],
["kiwi", "tomato", "avocado"],
["beans", "asparagus", "spinach"]
]
let dataObj = {};
const dataArr = [];
if (rows.length) {
keys = rows[0];
rows.forEach((row, i) => {
if(i==0)
return
dataObj = {}
keys.forEach((key, j) => {
dataObj[key] = row[j];
});
dataArr.push(dataObj);
});
}
console.log(dataArr)