-4

I am new to Typescript/Javascript and I am having trouble manipulating an array of data so I apologize in advance for my incompetency.

Given an array of objects with values such:

items = [{header: "h1", value: "header 1 test"}, {header: "h2", value: "header 2 test"}]

I want to be able to loop through each object in the array and take their values and turn them into a key:value pair object and insert that into a new array that should look like this.

myNewArray = [{"h1": "header 1 test"}, {"h2": "header 2 test"}]

I am working with Angular and TypeScript but I believe both Javascript and Typescript should work. Feel free to use any modern techniques. I have tried creating a new array, using ES6 [element.header]: [element.value] and it still giving me trouble.

Thanks!

obohP
  • 15
  • 5
  • Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output using the `[<>]` snippet editor. – mplungjan Sep 02 '20 at 07:52

3 Answers3

2

const items = [{header: "h1", value: "header 1 test"}, {header: "h2", value: "header 2 test"}];

const result = items.map(el => ({[el.header]: el.value}));
console.log(result);
MorKadosh
  • 5,846
  • 3
  • 25
  • 37
  • Thanks, this works as intended except the result is: result = [{h1: "header 1 test"}, {h2: "header 2 test"}] Is there any way to get the property into a string during the map conversion? i.e result = [{"h1": "header 1 test"}, {"h2: "header 2 test"}] – obohP Sep 02 '20 at 08:13
  • This is an array of objects, what do you mean? – MorKadosh Sep 02 '20 at 08:29
0

One way you can do this is to use the map operator on an array. In code this would look like this:

const myNewArray = items.map((item) => {
    const header = item.header;
    const value = item.value;

    return {
        [header]: value
    };
});

The map operator will loop through your array and call the defined function for each element. You can then transform the element to whatever value you want and the map operator will group them together into a new array.

Mathyn
  • 2,436
  • 2
  • 21
  • 33
0

Only thing tricky here is the need to use () to wrap the object you return in a map

const newObj = [{header: "h1", value: "header 1 test"}, {header: "h2", value: "header 2 test"}]
.map(item => ({[item.header]:item.value}))

console.log(newObj)
mplungjan
  • 169,008
  • 28
  • 173
  • 236