Home > Back-end >  Angualar - change object into array with specific structure
Angualar - change object into array with specific structure

Time:02-13

Good morning, could someone help me with changing Object like this

    {
    item1: "this is string field value",
    item2: "FF FF A2 C4h"
    }

And i need to get this format of array

[
 {
  id: item1, value: "this is string field value"
 },
 {
  id: item2, value: "FF FF A2 C4"
 }
]

I know how I could solve this, for example, using it Object.keys() or Object.values().

But I always get only one parameter out of two. And then the combination of these two results I am not able to put together. Therefore, I want to ask if anyone knows about a better / simpler solution. Or if someone could show me what I'm doing wrong and what is solution for this.

Thanks in advance

CodePudding user response:

You can use Object.entries() to get hold of both key and value at same time.

From MDN docs:

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs

Try something as below:

const someArray = Object.entries(someObject).map(([key, value]) => ({id: key, value: value}))

CodePudding user response:

With Object.keys(), you can work as below:

let input = {
    item1: "this is string field value",
    item2: "FF FF A2 C4h"
};

let result: {id: string, value: string}[] = [];

Object.keys(input).forEach(function(k) {
    let key = k as keyof typeof input;
    result.push({
        id: k,
        value: input[key]
    });
});

Sample Typescript Playground

  • Related