0

i can't get array b of object a with reduce in js

can you help me find the error?

const a = {
  dias:"valor",
  horas:"valor"
}

const b = campos.reduce((acc, el) => ([...acc, {
  title: el, field: el
}]), {})

desired result = [
 { title: 'dias', field: 'dias' },
 { title: 'horas', field: 'horas' },
]
2
  • be careful with the array name is a=campos Commented Feb 24, 2021 at 12:40
  • You can edit your question to fix typos. Commented Feb 24, 2021 at 12:53

1 Answer 1

1

You can use Object.keys().

const a = {
  dias: "valor",
  horas: "valor",
};

const b = Object.keys(a).map((key) => ({ title: key, field: key }));

console.log(b);

If you want the value of the property as the field instead, you can use Object.entries():

const a = {
  dias: "valor",
  horas: "valor",
};

const b = Object.entries(a).map(([key, value]) => ({
  title: key,
  field: value,
}));

console.log(b);

As a note, the [key, value] syntax is called array destructuring.

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

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.