0

I have a JSON array from DB, and I want it to manipulate. Currently it has discreet 8 elements, I want the array to manipulate it to get 2 elements, rest elements will be nested. My current JSON has this structure:

{
  "itemId": 1,
  "desc": [{
    "type": "A",
    "size": "xx",
    "count": 12,
    "price": 122
  },
  {
    "type": "A",
    "size": "xl",
    "count": 18,
    "price": 180
  },
  {
    "type": "B",
    "size": "xx",
    "count": 12,
    "price": 122
  },
  {
    "type": "B",
    "size": "xl",
    "count": 12,
    "price": 122
  }]
}

I want the data to be manipulated to come like this:

{
 "type": "A",
  "desc":{
    "size": "xx",
    "count": 12,
    "price": 122
  },
  {
    "size": "xl",
    "count": 12,
    "price": 122
  },
 },
  {
 "type": "B",
  "desc":{
    "size": "xx",
    "count": 12,
    "price": 122
  },
  {
    "size": "xl",
    "count": 12,
    "price": 122
  },
 }

I am using for each loop, but this is creating individual elements, i want just two elements in the resulting array. Any solution will be appreciated.

1
  • 3
    Your desired/output data-structure/schema seems to be malformed. Please correct it. Should it be [{"type": "A", "desc": [{...}, {...}]}, {...}]? Commented Apr 10, 2016 at 5:09

2 Answers 2

1

You could try something like this:

var new_data = {
    A: {type: 'A', desc: []},
    B: {type: 'B', desc: []}
};

$.each(data.desc, function( index, value ) {
  new_data[value.type].desc.push(value);
});

https://jsfiddle.net/5cnaxn04/

If you don't know the types you will get, you can build the object dynamically:

var new_data = {};

$.each(data.desc, function( index, value ) {
  if(typeof new_data[value.type] === "undefined") {
    new_data[value.type] = {type: value.type, desc: [value]}
  } else {
    new_data[value.type].desc.push(value);
  }
});

https://jsfiddle.net/5cnaxn04/1/

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

Comments

0

You have some syntax errors in your code, as you are using {} for both Arrays and Objects, so I'd guess from the context. You need a few loops to make the data look exactly to what you want.

See JSFiddle.

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.