-5

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!

1
  • Please visit the help center, take the tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output using the [<>] snippet editor. Commented Sep 2, 2020 at 7:52

3 Answers 3

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);

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

2 Comments

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"}]
This is an array of objects, what do you mean?
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.

Comments

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)

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.