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!

2

3 Answers 3

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)

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

Comments

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

Comments

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

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.