0

I have an array like this (each contain more than 2 key-values pairs,I just use 2 for the question)

[{"name":"Joe", "id":17}, {"name":"Bob", "id":17}, {"name":"Carl", "id": 35},{"name":"son", "id": 31},{"name":"smith", "id": 29},{"name":"tom", "id": 35}]

I would like to set a multidimensional object like this. for every DISTINC "id" and inside this "id" contain "id", "name" values .

{
'17' : {
    {"name":"Joe",
    "id":17},
    {"name":"Bob",
    "id":17}
},
'35' : {
    {"name":"Carl", "id": 35},
    {"name":"tom", "id": 35}
},
'31':{"name":"son", "id": 31}
},
 '29':{"name":"smith", "id": 29}
}

As you see I want to assign distinct "id" as key on first object

I think I may misuse brackets, sorry for that, please correct me on this too.

4
  • What's your question? How to create the muldimensional object or what's the best way to structured your data? Commented Dec 6, 2015 at 12:07
  • create the multidimensional as I said in the title . thanks Commented Dec 6, 2015 at 12:20
  • 1
    Why are you storing the id multiple times? Three times for 17 and 35. Seems redundant Commented Dec 6, 2015 at 13:02
  • right @Tdelang. as I said there many other values in the array anyway, consider if were any other . thanks Commented Dec 6, 2015 at 14:17

3 Answers 3

2

I'd be lazy and use underscore. It has a function called groupBy which does exactly what you need:

_.groupBy(arr, 'id');

JSFiddle.

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

1 Comment

this is not lazy since I have to read about underscore but @gre_gor answer is for the concept of the question , even thought I may probably use this
0

Loop over your data and add it to a new object or append it, depending if it already exists.

var data = [{"name":"Joe", "id":17}, {"name":"Bob", "id":17}, {"name":"Carl", "id": 35},{"name":"son", "id": 31},{"name":"smith", "id": 29},{"name":"tom", "id": 35}];

var new_data = {};

for (var i=0; i<data.length; i++)
{
    if (new_data.hasOwnProperty(data[i].id))
        new_data[data[i].id].push(data[i]);
    else
        new_data[data[i].id] = [data[i]];
}
document.getElementById("new_data").textContent = JSON.stringify(new_data, null, 4);
<pre id="new_data"></pre>

Comments

0

Why not just populate a new object?

var obj = {};

var arr = [{"name":"Joe", "id":17}, {"name":"Bob", "id":17}, {"name":"Carl", "id": 35},{"name":"son", "id": 31},{"name":"smith", "id": 29},{"name":"tom", "id": 35}];

arr.forEach(function(k) {
   obj[k.id] = k;
})

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.