简体   繁体   中英

Create array of key value from Object ES6

I have this Object

var obj = {
  'names-1-1': 0,
  'names-1-2': 0.94,
  'names-1-3': 0,
  'names-2-1': 0.95,
  'names-2-2': 0.96,
  'names-2-3': 0.2,
  'names-3-1': 0.96,
  'names-3-2': 99999,
  'names-3-3': 2.4
};

But i need a array of arrays(key, value) something like this:

   0 :{
        names-1-1 : 0
        names-1-2 : 0.94
        names-1-3 : 0
      }
   1 :{
        names-2-1 : 0.95
        names-2-2 : 0.96
        names-2-3 : 0.2
      }
   2 :{
        names-3-1 : 0.96
        names-3-2 : 99999
        names-3-3 : 2.4
      } 

where names-{index}-1 index its a var. How to aproach this using React & javascript ES6?

Object.keys has been around since ECMA 5.1

const obj = {
  test: 'some test',
  test2: 'another test'
};

const keys = Object.keys(obj); // ['test', 'test2']

Or Object.entries which was added in ECMA 2017

const obj = {
  test: 'some test',
  test2: 'another test'
};

const entries = Object.entries(obj);
// [['test', 'some test], ['test2', 'another test']]

You could do this:

myObject = {
    "names-1-1": .5,
    "names-1-2": .3,
    "names-2-1": .1,
    "names-2-2": .6
}
var out = [];
for (var i in myObject) {
    var index = i.substr(6,1);
    out[index-1] = out[index-1] || {};
    out[index-1][i] = myObject[i];
}
console.log(out);
//[{"names-1-1":0.5,"names-1-2":0.3},{"names-2-1":0.1,"names-2-2":0.6}]

You can use Array#reduce method to generate the array.

 var obj = { 'names-1-1': 0, 'names-1-2': 0.94, 'names-1-3': 0, 'names-2-1': 0.95, 'names-2-2': 0.96, 'names-2-3': 0.2, 'names-3-1': 0.96, 'names-3-2': 99999, 'names-3-3': 2.4}; var res = Object.keys(obj) // get all the keys // iterate to generate the result array .reduce(function(arr, k) { // get the index from property name using regex // or use k.split('-')[1] var i = k.match(/names-(\\d+)/)[1]; // define index if not defined arr[i - 1] = arr[i - 1] || {}; // set the property in the object arr[i - 1][k] = obj[k]; // return the array reference return arr; // set initial value as an empty array }, []); console.log(res); 

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