简体   繁体   中英

How to loop over objects and push the keys into an array?

I have an object which consists of newSales and oldSales and I am looping over them to get the key value pairs. I have been able to console log them but now I am stuck. How do I push those key value pairs in my array? This is a sample codepen

 const obj = { newSales: 1, oldSales: 0, anotherProp: 'something', etc: 'etc', values: 'numbers' } function myDataSet() { let dataSet = [] for (let key in obj) { if (obj.hasOwnProperty(key)) { console.log(`${key}: ${obj[key]}`) dataSet.push({ name: ['newSales', 'oldSales'], data: [1, 0] }) } } return dataSet } myDataSet();

The new Name in the object should be the name ie newSales and oldSales and data inside should be an array with the values 1 and 0. I appreciate all the help.

Expected output:

[ { name: ['newSales', 'oldSales'], data:[ 1,0 ] } ]

If I understood correctly, you want this.

Edited to have the outer array as required, although I don't understand its purpose.

let dataSet = [{
  name: Object.keys(obj),
  data: Object.values(obj)
}];

you might want something line this

 const obj = { newSales: 1, oldSales: 0, anotherProp: 'something', etc: 'etc', values: 'numbers' } let dataSet = [], names= [], data =[]; for (let key in obj) { if (obj.hasOwnProperty(key) && ["newSales", "oldSales"].indexOf(key) >= 0) { console.log(`${key}: ${obj[key]}`) data.push(obj[key]); names.push(key); } } dataSet.push({names:names, data:data}); console.log(dataSet)

You can get the list of an object's keys by calling Object.keys() , similarly for values:

 const obj = { newSales: 1, oldSales: 0 } function myDataSet() { let dataSet = [] dataSet.push({ 'name': Object.keys(obj), 'data': Object.values(obj) }); return dataSet; } console.log(myDataSet());

You could use Object.entries() and Array#reduce() :

 const obj = { newSales: 1, oldSales: 0 } const dataSet=[] dataSet.push(Object.entries(obj).reduce((acc,[key,value])=>{ acc.name.push(key) acc.data.push(value) return acc },{name:[],data:[]})); console.log(dataSet);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM