-1

How can I convert a javascript object into an array of objects? Array elements must be ordered by the index property in the original object:

Input:

var o = { "0gfbpa1508024708952": { title: "hi daughter", index: 3 }, "b8tl5k1508024741100": { title: "hi dad", index: 0 }, "cxr9x1508024697320": { title: "hi son", index: 2 }, "qua2802469732": { title: "hi cousin", index: 9007199254740991 }, "tck80i1508024731561": { title: "hi mom", index: 1 } }; 

Output:

[ {id: "b8tl5k1508024741100", title: "hi dad"}, // array index 0 {id: "tck80i1508024731561", title: "hi mom"}, // array index 1 {id: "cxr9x1508024697320", title: "hi son"}, // array index 2 {id: "0gfbpa1508024708952", title: "hi daughter"}, // array index 3 {id: "qua2802469732", title: "hi cousin"} // array index 4 ] 

This question only helps with the ordering/sorting of the array. It doesn't explain how to (1) transform the object key into the array object id property and (2) how to remove the index key from the array. There is transformation going on here, not just ordering/sorting based on object keys.

1

1 Answer 1

1
let o = { "0gfbpa1508024708952": { title: "hi daughter", index: 3 }, "b8tl5k1508024741100": { title: "hi dad", index: 0 }, "cxr9x1508024697320": { title: "hi son", index: 2 }, "qua2802469732": { title: "hi cousin", index: 9007199254740991 }, "tck80i1508024731561": { title: "hi mom", index: 1 } }, arr = []; for (let k in o) { let tmp = o[k]; tmp.id = k; arr.push(tmp); } arr.sort(function(a,b) { return a.index - b.index; }); for (let k in arr) delete arr[k].index; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.