[英]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: 但是我需要这样的arrays(key,value)数组:
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. 其中names-{index}-1
为其names-{index}-1
索引。 How to aproach this using React & javascript ES6? 如何使用React&JavaScript ES6来解决这个问题?
Object.keys has been around since ECMA 5.1 自ECMA 5.1起就存在Object.keys
const obj = {
test: 'some test',
test2: 'another test'
};
const keys = Object.keys(obj); // ['test', 'test2']
Or Object.entries which was added in ECMA 2017 或ECMA 2017中添加的Object.entries
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. 您可以使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.