0

I have object of object like this:

        const testik = {
        0: {
            name: "(REJ) - Rejected",
            value: 'rejected'
        },
        1: {
            name: "(VISA) - Received visa",
            value: 'received_visa'
        }
    }

And i want final Array of objects like this:

        const crossingStatusItems = [
        {
            id: '0',
            name: "(REJ) - Rejected",
            value: 'rejected'
        },
        {
            id: '1',
            name: "(VISA) - Received visa",
            value: 'received_visa'
        }]

Thanks for any help!

WooZy
  • 93
  • 1
  • 7
  • 1
    Does this answer your question? [How to convert object containing Objects into array of objects](https://stackoverflow.com/questions/26795643/how-to-convert-object-containing-objects-into-array-of-objects) – Tamir Abutbul Sep 20 '22 at 16:28
  • @TamirAbutbul Not exactly the same, OP needs to add the original key to the new element in the array as `id`. – kelsny Sep 20 '22 at 16:29

3 Answers3

3

Object.entries(testik) will return an array of the key-value pairs in your object. These can be mapped into an array of new object quite easily with the help of the spread operator:

Object.entries(testik).map(([id, v]) => ({...v, id}))

const testik = {
  0: {
    name: "(REJ) - Rejected",
    value: 'rejected'
  },
  1: {
    name: "(VISA) - Received visa",
    value: 'received_visa'
  }
}
const mapped = Object.entries(testik).map(([id, v]) => ({ ...v,
  id
}))
console.log(mapped)
spender
  • 117,338
  • 33
  • 229
  • 351
0

Try this

function toArray(obj) {
  return Object.keys(obj).map(function (key) {
    return {
      id: `${key}`,
      ...obj[key],
    };
  });
}

const testik = {
  0: {
    name: "(REJ) - Rejected",
    value: "rejected",
  },
  1: {
    name: "(VISA) - Received visa",
    value: "received_visa",
  },
};

const crossingStatusItems = toArray(testik);
console.log(crossingStatusItems);
Obie
  • 302
  • 3
  • 8
0

One way to to it would be use the Object.entries method like so:

function toArray(obj) {
    return Object.entries(obj).map(function ([id, value]) {
        return {
            ...value,
            id: id,
        };
    });
}

Or a shorter version:

function toArray(obj) {
    return Object.entries(obj).map(([id, value]) => ({ ...value, id }));
}
Cam Parry
  • 104
  • 1
  • 8