如何将对象转换为二维数组?
例如:
{ field : 'name',
value : 'peter',
field1 : 'email',
value1 : 'test@gmail.com',
field2 : 'id',
value2 : '2345',
............
.....
...
}
到
[['name', 'peter],['email','test@gmail.com'],['id','2345'] .......]
谢谢!
答案 0 :(得分:1)
您可以查看field
并获取新数组的值。
var object = { field: 'name', value: 'peter', field1: 'email', value1: 'test@gmail.com', field2: 'id', value2: '2345'},
array = Object.keys(object).reduce((r, k) =>
r.concat(k.slice(0, 5) === 'field'? [[object[k], object['value' + k.slice(5)]]] : [])
, []);
console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)
let obj = {
field: 'name',
value: 'peter',
field1: 'email',
value1: 'test@gmail.com',
field2: 'id',
value2: '2345'
};
let result = Object.keys(obj)
.filter(key => key.indexOf("field") === 0) // we're only interested in the "fieldX" keys
.map(field => [obj[field], obj[field.replace("field", "value")]]); // build the array from the "fieldX"-keys
console.log(result);
答案 2 :(得分:1)
let obj = {
field : 'name',
value : 'peter',
field1 : 'email',
value1 : 'test@gmail.com',
field2 : 'id',
value2 : '2345'
};
let results = [];
Object.values(obj).forEach((e, i, arr) => {
if (!(i % 2)) {
results.push([e, arr[i+1]]);
}
});
console.log(results);

答案 3 :(得分:1)
尝试此功能,它将为您完成:
var objectToPairs = function(object) {
var array = [];
for (var key in object) {
if (object.hasOwnProperty(key)) {
if (key.indexOf('field') === 0) {
var index = key.replace(/^\D+/g, '');
var valueKey = 'value' + index;
if (object.hasOwnProperty(key)) {
array.push([object[key], object[valueKey]]);
}
}
}
}
return array;
}
JSFIddle: