I am trying to place my _rows values into my object value , however i have tried running a loop but i wasnt able to get the data out , the script i used is
let _columns = ["Name", "age", "phone"]
let _rows = [[{ value: 'john' }, { value: '22' }, { value: '999' }], [{ value: 'Bob' }, { value: '21' }, { value: '222' }]]
let res = {}
for (let i = 0; i < _rows.length; i++) {
for (let a = 0; a < _columns.length; a++) {
console.log(_rows[i][a].value)
}
res = _columns.reduce((acc,curr)=> (acc[curr]="data",acc),{});
console.log(res)
res = {}
}
on my console.log , it prints
The target output should be
{Name: 'john', age: '22', phone: '999'}
{Name: 'bob', age: '21', phone: '222'}
you can use
array.map to build another array from _rows
foreach value you have to check if columns exist
if (_columns[index]) {
if yes add in the new object the value under column name
res[_columns[index]] = property.value;
let _columns = ["Name", "age", "phone"]
let _rows = [[{ value: 'john' }, { value: '22' }, { value: '999' }], [{ value: 'Bob' }, { value: '21' }, { value: '222' }]];
let result = _rows.map(one => {
let res = {};
one.forEach((property, index) => {
if (_columns[index]) {
res[_columns[index]] = property.value;
}
});
return res;
});
console.log(result);
If you want to stick with reduce, just make this small change to get the actual value instead of the hardcode string "data". You need to use the optional parameter currentIndex of the reduce callback, then use the index to access the row item for the value.
let _columns = ["Name", "age", "phone"]
let _rows = [[{ value: 'john' }, { value: '22' }, { value: '999' }], [{ value: 'Bob' }, { value: '21' }, { value: '222' }]]
let res = {}
for (let i = 0; i < _rows.length; i++) {
for (let a = 0; a < _columns.length; a++) {
console.log(_rows[i][a].value)
}
res = _columns.reduce((acc,curr,index)=> (acc[curr]=_rows[i][index].value,acc),{});
console.log(res)
res = {}
}
However, when dealing with rows and columns in your case, since the array index is important, using old-school nested for-loop might be much more clear sometimes. My experience is, when you need the array index anyway, try not to be fancy and go for regular for-loop.
let _columns = ["Name", "age", "phone"]
let _rows = [[{ value: 'john' }, { value: '22' }, { value: '999' }], [{ value: 'Bob' }, { value: '21' }, { value: '222' }]]
for(let i = 0; i < _rows.length; i++)
{
let res = {};
for(let j = 0; j < _columns.length; j++)
{
res[_columns[j]] = _rows[i][j].value
}
console.log(res);
}
A double Arry.map will do the trick
let _columns = ["Name", "age", "phone"]
let _rows = [
[{ value: 'john' }, { value: '22' }, { value: '999' }],
[{ value: 'Bob' }, { value: '21' }, { value: '222' }]
];
const output = _rows.map((row) => row.map((item, index) => ({ [_columns[index]]: item.value })));
console.log(output)