sinnede
sinnede

Reputation: 93

Convert objects into array with same object key

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

Upvotes: 1

Views: 128

Answers (4)

larrydahooster
larrydahooster

Reputation: 4163

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

Upvotes: 0

yaya
yaya

Reputation: 8243

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)

Upvotes: 1

Prince Devadoss
Prince Devadoss

Reputation: 416

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.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386540

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

Upvotes: 0

Related Questions