从Object ES6创建键值数组

时间:2017-11-30 18:34:48

标签: javascript arrays ecmascript-6

我有这个对象

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

但是我需要一个像这样的数组(键,值)数组:

   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
      } 

其中names-{index}-1索引其变量。 如何使用React& amp; javascript ES6?

3 个答案:

答案 0 :(得分:0)

Object.keys自ECMA 5.1以来一直存在

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

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

Object.entries已在ECMA 2017中添加

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

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

答案 1 :(得分:0)

你可以这样做:

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

答案 2 :(得分:0)

您可以使用Array#reduce方法生成数组。



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