2

I have an array

const a = [
  { name: "read-web-courses" },
  { name: "example" },
  { name: "t_gql" },
  { name: "ddddd" },
];

I am trying it to reduce it to the below given output , However I am stuck

Output

{0:"read-web-courses",1:"example",2:"t_gql",3:"ddddd"}
1
  • 1
    What got you stuck? Commented Nov 7, 2020 at 18:18

3 Answers 3

3

You could map the wanted property and assign the pairs to the object.

const
    array = [{ name: "read-web-courses" }, { name: "example" }, { name: "t_gql" }, { name: "ddddd" }],
    result = Object.assign({}, array.map(({ name }) => name));

console.log(result);

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

Comments

1

You can use Array.reduce like below.

  const a = [
    { name: "read-web-courses" },
    { name: "example" },
    { name: "t_gql" },
    { name: "ddddd" },
  ];
  
  const convert = arr => (
    arr.reduce((total, value, index) => {
      total[index] = value.name;
      return total;
    }, {})
  )

  console.log(convert(a));

Comments

1

This is accomplished using Array#reduce, where you can use the index from the reduce callback as the key of the new object:

const a = [ { name: "read-web-courses" }, { name: "example" }, { name: "t_gql" }, { name: "ddddd" }];

const res = a.reduce((r, o, i) => {
  r[i] = o.name;
  return r;
}, {});

console.log(res);

Also one more approach using Object#fromEntries and Array#map, where each object is converted to an array of key, value pairs:

const a = [ { name: "read-web-courses" }, { name: "example" }, { name: "t_gql" }, { name: "ddddd" }];

const res = Object.fromEntries(a.map((o, i) => [i, o.name]));
console.log(res)

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.