prajeesh
prajeesh

Reputation: 2382

Format a javascript object into a specific structure

i have a javascript object as follows

obj = {"account_id-0":null,"option_item_id-0":1,"value-0":"wer","account_id-1":null,"option_item_id-1":2,"value-1":"kkk","account_id-2":null,"option_item_id-2":3,"value-2":"qqqqq"
....
 "account_id-n":null,"option_item_id-n":6,"value-n":"see"
}

From the above object, i need to create the following structure

{"0": {
        account_id: null,
        option_item_id: 1,
        value: "wer"
      },
 "1": {
        account_id: null,
        option_item_id: 2,
        value: "kkk"
      },
 "2": {
        account_id: null,
        option_item_id: 2,
        value: "qqqqq"
      },
  .
  .
  .
 "n": {
        account_id: null,
        option_item_id: 6,
        value: "see"
      }
}      

Any idea on how to implement this?

Upvotes: 1

Views: 66

Answers (3)

Stefan Octavian
Stefan Octavian

Reputation: 620

Try this:

var keys = Object.keys(obj), i = 0
var arr = [], o = {}
for(var k in keys) {
    if(keys[k].match(/\d*$/m) == i) {
       o[keys[k].replace(/-\d*$/m,'')] = obj[keys[k]]
    } else {
         i++ 
         arr.push(o)
         o = {} 
     }
 }

Here I am using an array instead of an object with the keys "0", "1", " 2", ... "n". I think it's way more convenient.

Upvotes: 0

Garfield
Garfield

Reputation: 2537

var obj = {
  "account_id-0": null,
  "option_item_id-0": 1,
  "value-0": "wer",
  "account_id-1": null,
  "option_item_id-1": 2,
  "value-1": "kkk",
  "account_id-2": null,
  "option_item_id-2": 3,
  "value-2": "qqqqq"
};

var props = [];

function getObj(ind) {
  for (var p in props) {
    if (ind === p) {
      return props[p];
    }
  }
}

for (var prop in obj) {
  var parts = prop.split('-');
  var key = parts[0];
  var indx = parts[1];
  var tmp = getObj(indx);
  if (tmp == undefined) {
    var x = {};
    x[indx] = {};
    x[indx][key] = obj[prop];
    props.push(x);
  } else {
    tmp[indx][key] = obj[prop];
  }
}

console.log(props);

This should be the straight forward way of maniplulating the object array with simple split() function.

Upvotes: 1

31piy
31piy

Reputation: 23859

You can iterate through the all the keys, and use Array#reduce to contruct the resultant object.

let obj = {
  "account_id-0": null,
  "option_item_id-0": 1,
  "value-0": "wer",
  "account_id-1": null,
  "option_item_id-1": 2,
  "value-1": "kkk",
  "account_id-2": null,
  "option_item_id-2": 3,
  "value-2": "qqqqq",
  "account_id-n": null,
  "option_item_id-n": 6,
  "value-0": "see"
};

let result = Object.keys(obj).reduce((res, item) => {
  let [key, index] = item.split('-');

  if (!res[index]) {
    res[index] = {};
  }

  res[index][key] = obj[item];
  return res;
}, {});

console.log(result);

Upvotes: 4

Related Questions