[英]Convert object to 2d array
How I can transform an object to a 2d array? 如何将对象转换为2D数组?
for example : 例如 :
{ field : 'name',
value : 'peter',
field1 : 'email',
value1 : 'test@gmail.com',
field2 : 'id',
value2 : '2345',
............
.....
...
}
to 至
[['name', 'peter],['email','test@gmail.com'],['id','2345'] .......]
thanks! 谢谢!
You could check the field
and get the value for a new array. 您可以检查该
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; }
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);
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);
Try this function, it will do it for you: 试试这个功能,它会为你做的:
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: 的jsfiddle:
https://jsfiddle.net/mucwvqpz/1/ https://jsfiddle.net/mucwvqpz/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.