0

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?

4 Answers 4

2

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.

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

1 Comment

thank you for showing the complete way, i didnot use stringify, now i do. nice!
2

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.

Comments

1

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];
        }

    }
}

Comments

1

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

Comments

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.