Typescript object values to array

How to convert type object keys into an array of strings type in typescript

which gives me [«a» | «b» | «c»] which is close, but not what I’m looking for in this case. I need an array that always contains all the key strings in the given type object. The only way I know to enforce this, for example when a user adds a new key to the object that the key is also added to the array is via something like this.

ok, now can you explain how such a String Array Literal type would be useful? Because maybe the underlying problem is the one you should be asking. Types are erased in the output, so the only purpose they serve is for static type checking, or to construct other types for static type checking. In the later case keyof InputObjectType is all you need. Otherwise this seems like an abstract exercise with no purpose, and probably doesn’t belong on SO. In other words, let’s say what you ask isn’t possible, which I think it isn’t. Make the case to The Typescript folks why it should be.

Читайте также:  Python import path environment

What you have should work (though I’m using v3.9). When I perform those same steps I get («a»|»b»|»c»)[] which I believe is exactly what you want. If instead you want an array that dynamically contains all those values, I don’t believe that is possible as the Type doesn’t exist at runtime.

4 Answers 4

Not sure if you’re still looking for a solution here, but hopefully this helps.

If what you want is a type that requires that the variable be an array of strings only containing values equal to the keys of your object, then what you have listed should work.

type InputObjectType = < a: string b: number c: <>> type AllPossibleKeys = (keyof InputObjectType)[] 

AllPossibleKeys will be a type equal to («a»|»b»|»c»)[] . This looks to be what you’ve asked for, but there is a caveat with how I’m guessing you want to use this.

const fieldArray1: AllPossibleKeys = ['a', 'b', 'c']; //valid const fieldArray2: AllPossibleKeys = ['a', 'b', 'c', 'd']; //will throw a Typescript error const fieldArray3: AllPossibleKeys = ['a', 'b']; //this is also valid though as each member is a valid value 

If you instead want an array of all the keys in a type, there’s not a way to do this explicitly that I’m aware of. However, if you are able to use an interface instead of a type, then you can do the following:

import < keys >from 'lodash'; interface InputObject = < a: string b: number c: <>> class InputObjectStub implements InputObject < a = null; b = null; c = null; >const fieldArray1 = keys(new InputObjectStub()); //returns ['a', 'b', 'c'] 

Note though, that this won’t enforce optional attributes. If you need to do that, change your class definition to class InputObjectStub implements Required

Читайте также:  Gradient button animation css

Источник

Typescript object values to array

Last updated: Jan 20, 2023
Reading time · 2 min

banner

# Convert an object to an Array in TypeScript

There are three ways to convert an object to an array in TypeScript:

  1. Object.keys() — returns an array containing the object’s keys.
  2. Object.values() — returns an array containing the object’s values.
  3. Object.entries() — returns an array containing key-value pair arrays.
Copied!
const obj = name: 'Bobby', country: 'Chile' >; const keys = Object.keys(obj); console.log(keys); // 👉️ ['name', 'country'] const values = Object.values(obj); console.log(values); // 👉️ ['Bobby', 'Chile'] const entries = Object.entries(obj); console.log(entries); // 👉️ [['name', 'Bobby'], ['country', 'Chile']]

The first example uses the Object.keys method to get an array of the object’s keys.

The method returns an array of strings where the keys of the object are in the same order as provided by a for. in loop.

Copied!
// 👇️️ ['one', 'two'] console.log(Object.keys(one: 1, two: 2>));

You can then iterate over the array of keys as follows.

Copied!
const obj = name: 'Bobby', country: 'Chile' >; const keys = Object.keys(obj) as (keyof typeof obj)[]; console.log(keys); // 👉️ ['name', 'country'] keys.forEach((key) => // 👇️ name Bobby, country Chile console.log(key, obj[key]); >);

# Convert an Object’s values to an Array in TypeScript

You can use Object.values method to convert an object’s values to an array.

Copied!
const obj = name: 'Bobby Hadz', country: 'Chile' >; const values = Object.values(obj); console.log(values); // 👉️ ['Bobby Hadz', 'Chile']

Similarly to the keys method, the values are added to the array in the same order as that provided by a for. in loop.

# Convert an Object’s entries to an Array in TypeScript

Use the Object.entries method to convert an object to an array of key-value pair arrays.

Copied!
const obj = name: 'Bobby Hadz', country: 'Chile' >; // 👇️ const entries: [string, string][] const entries = Object.entries(obj); console.log(entries); // 👉️ [['name', 'Bobby Hadz'], ['country', 'Chile']]

The nested arrays consist of 2 elements — the key and the value.

You can iterate over the array of key-value pairs by using the forEach() method.

Copied!
const obj = name: 'Bobby', country: 'Chile' >; // 👇️ const entries: [string, string][] const entries = Object.entries(obj); console.log(entries); // 👉️ [['name', 'Bobby'], ['country', 'Chile']] entries.forEach(([key, value]) => // 👇️ name Bobby, country Chile console.log(key, value); >);

Notice that we used array destructuring to destructure the key and value from the array.

Here is an example of how array destructuring works.

Copied!
const arr = ['bobby', 'hadz']; const [a, b] = arr; console.log(a); // 👉️ "bobby" console.log(b); // 👉️ "hadz"

We’re basically unpacking the array’s elements into variables. Note that the order is preserved.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to Convert Object to/from Array in Typescript

Typescript is a superset of javascript with compile type checking.

In Application development, We used to get the use cases where data was retrieved from REST API/Database in the form of Array/Object, so need to convert this to Object/Array.

Every developer used to get these user cases during development.

Let us see ways to convert Objects to/from Arrays in javascript/Typescript/Angular applications.

First, we will see how the object Array creates is in typescript.

An array of Objects Declaration and Initialization

For example, an array contains model data like the one below.

[  id: 1, name: "Kiran" >,  id: 2, name: "Tom" >,  id: 3, name: "John" >, ];

Next, is to create an interface that represents the data modal.

export interface Emp  id: number; name: string; > const arr: Emp[] = [  id: 1, name: "Kiran" >,  id: 2, name: "Tom" >,  id: 3, name: "John" >, ];

How to convert Object to Array Typescript Example

This section will see how we can convert Objects to Array in Angular and Typescript with examples.

Typescript Code

Let us assume that you have an object declared with multiple properties.

First Get the named keys using object.keys() method.

This method retrieves keys from the given object and returns an array of keys.

Using the map() method with a defined callback. And callback is executed for each element of an object.

var employees =  kiran:  age: 30, salary: 10000 >, john:  age: 35, salary: 15000 >, Tom:  age: 21, salary: 5000 >, >; let arr = []; Object.keys(employees).map(function (key)  arr.push(< [key]: employees[key] >); return arr; >); console.log("Object=", employees); console.log("Array=", arr);

Typescript Object to Array with Example

Angular Code

For example, object data contains the following properties.

let empdata =  name: "Kiran", age: 30, salary: 10000, >;

First Create an Interface that represents the above.

export interface Emp  name: string; age: number; salary: number; >

In the Component, Create an empty array.

Add the object to an array using the push method

This pushes objects to array and output are

0:name: "kiran", age: 45, salary: 2000> length:1

If you want to convert object properties — name, age, salary

let emp =  name: "kiran", age: 45, salary: 2000, >; let array = []; for (let key in emp)  if (emp.hasOwnProperty(key))  array.push(emp[key]); > > console.log(array);

There are many ways we can do a conversion depending on the object structure.

using Array Push method example

Declared object and empty array using the array push method. we can convert to Array.

let myObject =  name: "kiran", age: 45, salary: 2000, >; let myArray = []; myArray.push(myObject); console.log(myArray);
Array(1)0: name: "kiran", age: 45, salary: 2000>length: 1__proto__: Array(0)

using Spread Operator and Object.assign() method example

we can convert array objects to Single objects.

var array = [ Kiran: "30" >,  Tom: "50" >], object = Object.assign(<>, . array); console.log(object);

Conclusion

To Sum up, Learned to Convert objects to/from Arrays in Typescript with examples.

Источник

How to convert object values to array in typescript?

Today, I’m going to show you how to convert object values to array in typescript, here we use some javascript Objects method like Object.values() method.

Sometime’s we need to create array from object values and that’s why we simple method Object.values()

interface User   id: number;  name: string;  domain?: string;  age?: number;  isActive?: boolean; >  let user: User =   id: 1,  name: "infinitbility",  domain: "infinitbility.com",  age: 2,  isActive: 1 >;  let userKeys = Object.values(user).map(key => return key>); 

When you run above code you will get all your objects property in array, check below output image.

Output#

TypeScript, convert object values to array example

TypeScript, convert object values to array example

Источник

Оцените статью