0

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]

6 Answers 6

1

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)
})

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

Comments

0

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);

Comments

0

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);

Comments

0

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);

Comments

0

You can write the following

data = [
   {
  AValuv: 6,
 BValuv: 8928,
 CValuv: 2553
}
]

let name = Object.keys(data[0])
let value = Object.values(data[0])

Comments

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

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.