doniyor
doniyor

Reputation: 37846

json object split into two json objects

I have this JSON Object

{1: "test projekt", 4: "Second Project", 
 5: "Third Project", 6: "Fourth Project", 
 7: "5th one", 8: "6th one dude", 
 uhash: "7021a11332508b6e30d3b6d3e95180398228b0e4010fc3f05db81e80"}

i want to split it into:

{1: "test projekt", 4: "Second Project", 
 5: "Third Project", 6: "Fourth Project", 
 7: "5th one", 8: "6th one dude"}

and

{uhash: "7021a11332508b6e30d3b6d3e95180398228b0e4010fc3f05db81e80"}

how can I do it in js?

Upvotes: 0

Views: 1676

Answers (4)

mcn
mcn

Reputation: 721

This might help

function popAttributeFromData (attrs, data) {
  for (var key in data) {
    if(key === attrs) {
      var result = {
        attrs: data[attrs]
      };
      delete data[attrs];
      return result;
    }
  }
  return null;
}

What it does it iterating through the keys from data until the key matches with the passed parameter attrs.

Here is the result enter image description here

PLAYGROUND

Upvotes: 1

Guffa
Guffa

Reputation: 700222

The easiest way to manipulate JSON is to parse it into objects, manipulate the objects and then create JSON from the objects:

var o = JSON.parse(json);

var o2 = { uhash: o.uhash };
delete o.uhash;

var json1 = JSON.stringify(o);
var json2 = JSON.stringify(o2);

Note: The JSON object is not supported in older browers, e.g. IE 7.

Upvotes: 2

Kinnza
Kinnza

Reputation: 1301

something like this ?

var secondObj = {uhash: firstObj.uhash};
delete firstObj.uhash;

for something more complex you can use underscore : underscorejs. take a look at groupBy or map. depends on what exactly do you need.

Upvotes: 2

James Long
James Long

Reputation: 4736

The for ... in loop will iterate over object keys. Be sure to limit it using the hasOwnProperty method otherwise for ... in will find all inherited keys of the object. Once you can iterate over the object, all you need to do is check the keys and populate two other objects.

var numbers = {},
    uhash   = {},
    prop    = '';

for (prop in json) {
    if (json.hasOwnProperty(prop)) {

        if (!isNaN(prop)) {
            numbers[prop] = json[prop];
        } else {
            uhash[prop] = json[prop];
        }

    }
}

Upvotes: 1

Related Questions