1

I have an object of data and I want to convert it into normal array without changing the index of the object.

This objects

let data = {
  123: {id: 123, name: "John"}
  456: {id: 456, name: "Doe"}
  789: {id: 789, name: "Maria"}
}

and convert to array with length, without the auto generated index e.g. 0,1,3

I already tried something like this

let data = {
  123: {id: 123, name: "John"},
  456: {id: 456, name: "Doe"},
  789: {id: 789, name: "Maria"}
}
let item = [];
for (var prop in data) {
   item.push(data[prop])
}

Actual Result:

0: {id: 123, name: "John"}
1: {id: 456, name: "Doe"}
2: {id: 789, name: "Maria"}
length: 3
__proto__: Array(0)

Expected result:

123: {id: 123, name: "John"}
456: {id: 456, name: "Doe"}
789: {id: 789, name: "Maria"}
length: 3
__proto__: Array(0)
​

How can i achieve it?

Please help

8
  • 1
    May I ask why you'd want to do this? You can use numbers as the keys, but wouldn't you much rather keep your current format? Commented Jun 4, 2019 at 12:49
  • 1
    Your expected result isn't really possible (as you have it displayed with length of 3) - as @NinaScholz pointed out, it's a sparse array. Setting a value at the index of 789 will create an array of length 790 Commented Jun 4, 2019 at 12:51
  • 1
    this is a bad practice to make an array with empty slots aka sparse array. Commented Jun 4, 2019 at 12:52
  • Furthermore, there will be no way to access your values efficiently. You would have to filter the, in this case, 790 items to remove the undefined values. Commented Jun 4, 2019 at 12:53
  • @TimVN this will help me on updating the item based on the index key.. too much nested object data.. so I was thinking updating the item with key will save performance and wont kill the browser Commented Jun 4, 2019 at 12:55

4 Answers 4

1

just change: item.push(data[prop]) to item[prop] = data[prop]

but it will become a sparse array. (and it's size won't be 3 as you expect)

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

5 Comments

Isn't 'let item = {}' where he is coming from? Also be careful with the wording 'associative array'. An object is NOT an associative array. Generally there is not such a thing in JS.
@larrydahooster he used let item = [] in his codes.and i know that there isn't associative array in js, i used this word because it helps to undestand it. is there any reason i should be careful about it?
@siney71 yes, it's not possible in js to have "an array with size 3 with custom indices". but you can use objects ( like : let item = {} and then set indices.) .
@yayapro but the object breaks my ordering, it is already in order from API
@larrydahooster got what you meant. updated answer.
0

With the given indices, you get a sparse array, because of the holes.

let data = { 123: { id: 123, name: "John" }, 456: { id: 456, name: "Doe" }, 789: { id: 789, name: "Maria" } },
    array = Object.assign([], data);
    
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

4 Comments

Too much undefined... and it also breaks the in order of the data fetched from API.. Question: is there a way to maintain the ordering from API even when you change the array to object?
what do you mean with order? how should the array look like?
Something like, I will convert the data from array to object then the ordering of the object still the same with the array, is that possible?
@siney71 this doesn't add undeinfed. It's just how it looks in Stack snippets. Check your browser's console. Other indices will be holes
0

We can achieve this by below code, but the indexes other than 123, 456, 789 will have undefined in your array.

let data = {
  123: {id: 123, name: "John"},
  456: {id: 456, name: "Doe"},
  789: {id: 789, name: "Maria"}
}
let item = [];
for (var prop in data) {
   item[prop] = data[prop];
}

console.log(item);

But in other place it will have undefined values, the array length will be 789. We can't have our own index in array. When we try to give, it will automatically assign undefined for the remaining indexes.

3 Comments

Other indices will be holes and will not have undefined as value (Snippet shows holes as undefined. You can verify in your browser's console)
Thank you. I meant to say that if he tries to access other index of that array, it will give undefined.
@siney71 Yes it's not possible to have an array with custom size with custom indices. If you want to access it based on the give index, you can use normal object with given keys and values.
0

I actually don't know your motivation to store it as you desire (that is not possible at all), but I assume you want to do it to maintain some kind of order and ensure that when you iterate over the array, you maintain the order?

A very common practice to maintain order of objects is to decouple the sorted index from the object itself.

You just need a sorting function that creates your index.

const sortedIndex = [123, 456, 789];

const unsortedData = {
  456: {id: 456, name: "Doe"}
  123: {id: 123, name: "John"}
  789: {id: 789, name: "Maria"}
}

sortedIndex.foreach(index => { item = unsortedData[index]; })

2 Comments

Thank you. can you help me what wrong with this ``` let sortedIndex = [123, 456, 789, 111, 222]; let item={} let unsortedData = { 456: {id: 456, name: "Doe"}, 123: {id: 123, name: "John"}, 789: {id: 789, name: "Maria"}, 111: {id: 111, name: "One"}, 222: {id: 222, name: "Two"}, } sortedIndex.map( (i,idx) => { return item[i] = unsortedData[i] }) console.log(item) ``` the object is not in order yet.
nvm. got it now. Thanks

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.