0

How I can transform an object to a 2d array?

for example :

{ field : 'name',
  value : 'peter',
  field1 : 'email',
  value1 : '[email protected]',
  field2 : 'id',
  value2 : '2345',
  ............
  .....
  ...
 }

to

  [['name', 'peter],['email','[email protected]'],['id','2345'] .......]

thanks!

2
  • Sure, but my English is not good, I try to find the solution by google search but still no idea on it Commented Mar 22, 2017 at 10:10
  • Programming doesn't work like cooking. In most cases there is no ready recipe for your specific problem. You have to find it yourself. Begin from here Commented Mar 22, 2017 at 10:18

4 Answers 4

2

let obj = {
  field: 'name',
  value: 'peter',
  field1: 'email',
  value1: '[email protected]',
  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);

Sign up to request clarification or add additional context in comments.

Comments

1

    let obj = {
      field : 'name',
      value : 'peter',
      field1 : 'email',
      value1 : '[email protected]',
      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);

Comments

1

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:

https://jsfiddle.net/mucwvqpz/1/

Comments

1

You could check the field and get the value for a new array.

var object = { field: 'name', value: 'peter', field1: 'email', value1: '[email protected]', 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 Comment

Thats not what is required

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.