I m getting following result through query in nodejs.
data = [
{
AValuv: 6,
BValuv: 8928,
CValuv: 2553
}
];
now I through forEach how to split them in two array and push them in the to get the required result.
let name=[];
let value=[];
name=[AValuv, BValuv, CValuv]
value=[6, 8928, 2553]
That is pretty easy in JavaScript you can use Object.keys()
and Object.values()
to get the keys and the values of the object.
data=[ { AValuv: 6, BValuv: 8928, CValuv: 2553 } ] data.forEach((elem) => { let vals = Object.values(elem); let keys = Object.keys(elem); console.log(vals) console.log(keys) })
You can do the following,
let data = [{'AValuv': 6, 'BValuv': 8928, 'CValuv': 2553}] let name = []; let value = []; data.forEach(item => { Object.keys(item).forEach(key => { name.push(key); value.push(item[key]); }); }); console.log(name); console.log(value);
You could use Array.prototype.forEeach()
once on the array, and then parse the objects with Object.entries()
and use Array.prototype.forEeach()
once again.
const data = [{ AValuv: 6, BValuv: 8928, CValuv: 2553 } ]; const name = []; const value = []; data.forEach(x => Object.entries(x).forEach(([k, v]) => { name.push(k); value.push(v); }) ); console.log(name); console.log(value);
data = [ { AValuv: 6, BValuv: 8928, CValuv: 2553 } ]; let name = []; let value = []; data.forEach(o => { name.push(...Object.keys(o)); value.push(...Object.values(o)); }); console.log(name, value);
You can write the following
data = [ { AValuv: 6, BValuv: 8928, CValuv: 2553 } ] let name = Object.keys(data[0]) let value = Object.values(data[0])
Like this:
const data = [{
AValuv: 6,
BValuv: 8928,
CValuv: 2553
}];
let name=[];
let value=[];
for (const [key, value] of Object.entries(data[0])) {
name.push(key);
value.push(value);
}
For more information see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.