0

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

1
  • Do you need {id: item1} or {id: "item1"} (string value) ? Commented Feb 13, 2022 at 7:31

2 Answers 2

3

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}))
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing thats what i need. I completely forgot about Object.entries () and how to use it in this case. Thank you.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.