-1

This is my array of Object. I want to convert my first value into key & Second value into value only. Please go through question and i have also attached my desired output.

 [
  {
    "name": "Unknown",
    "value": "RAHUL"
  },
  {
    "name": "FirstName",
    "value": "WILLEKE LISELOTTE"
  },
  {
    "name": "LastName",
    "value": "DE BRUIJN"
  }
]

I want my Object as

{
"Unknown": "RAHUL"

},
{
"FirstName": "WILLEKE LISELOTTE"
},
{
"LastName": "DE BRUIJN"
}
1
  • 2
    I want my Object as that's not an object, it's several objects separated by commas Commented Aug 17, 2021 at 16:28

2 Answers 2

0

IF you mean to create a new array, then simply map the original array. You don't need to create a new array and push into it, that's just redundant code:

const testData = [{
    "name": "Unknown",
    "value": "RAHUL"
  },
  {
    "name": "FirstName",
    "value": "WILLEKE LISELOTTE"
  },
  {
    "name": "LastName",
    "value": "DE BRUIJN"
  }
];

const newData = testData.map(nameObject => {
  return {
    [nameObject.name]: nameObject.value
  }
});
console.log(newData);

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

2 Comments

Like in the dupe target
Thanks - I did look but didn't see that specific Q/A - good find @Andreas
-1

You just have to use brackets for [value.name] to perform achieve this.

var arr = []

testdata.map((value) => {
    arr.push({ [value.name]: value.value })
})

6 Comments

You asked a question then you answered it yourself? why asking if you already have the answer?
@AdilBimzagh That's totally valid. Although in this case there are definitely already multiple other questions with the exact same problem.
This results in an array. OP said he wants an object.
@James This is the OP o.O
@Andreas understood. Point still stands.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.