-1

It is hard to put into words, so If anyone could help me with the title of the question, thanks in advance. At the end of the day, I have an array like so;

[ 
  {
    field: "firstname",
    value: "John"
  },
  {
    field: "lastname",
    value: "Doe"
  },
  {
    field: "hobbies",
    value: "singing, basketball"
  },
]

and the desired output will be like below;


[ 
  {
   "firstname":"John"
  },
  {
    "lastname":"Doe"
  },
  {
    "hobbies" :"singing, basketball"
  },
]

The closest question I could find similar to mine was this one: How to convert an array into an object in javascript with mapped key-value pairs?

1
  • The desired result is of questionable usefulness, compared to a single "person" object with well-known property names. Commented Sep 20, 2022 at 16:28

2 Answers 2

3

Use map and return object, where key will be obj.field and value as obj.value
i.e. {[obj.field]: obj.value}

let output = [ 
    {
        field: "firstname",
        value: "John"
    },
    {
        field: "lastname",
        value: "Doe"
    },
    {
        field: "hobbies",
        value: "singing, basketball"
    },
].map(a => ({[a.field]: a.value}))

console.log(output)

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

1 Comment

Answers which explain code are more often upvoted and less likely to be downvoted that answers which merely regurgitate code.
0

You can use map to set the field property to the key, and value property to the value

const data = [ {
    field: "firstname",
    value: "John"
  },
  {
    field: "lastname",
    value: "Doe"
  },
  {
    field: "hobbies",
    value: "singing, basketball"
  } ]

let result = data.map(({ field, value }) => ({[field]: value}));

console.log(result)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.