How I can transform an object to a 2d array?
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.
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:
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.