mfarhan
mfarhan

Reputation: 67

Typescript problem with getting values of object

I want to get values from

[{"code":"RRR","name":"Name","rate":"1.17","$key":"MeJy8ClJvJy"}]

I used Object.values(obj) and i am getting same

[{"code":"RRR","name":"Name","rate":"1.17","$key":"MeJy8ClJvJy"}]

while i tried using

    function* values(obj: string) {
      for (let prop of Object.keys(obj)) yield obj[prop as any];
    }

as well as

Object.keys(obj).map(k => obj[k as any]);

both these yielded me

 ["[", "{", "\"", "c", "o", "d", "e", "\"", ":", "\"", "R", "R", "R", "\"", ",", "\"", "n", "a", "m", "e", "\"", ":", "\"", "N","a","m","e" "\"", ",", "\"", "r", "a", "t", "e", "\"", ":", "\"", "1", ".","1", "7", .....

on chrome Version 91.0.4472.164 (Official Build) (64-bit) but funny thing is using TS Playground log is same

[{"code":"RRR","name":"Name","rate":"1.17","$key":"MeJy8ClJvJy"}]

but if i am removing [] from this everything works fine and as i am intending it to work. But only problem, I am getting data in only this way. I am using typescript 4.3.5 and angular 12.1. Thanks in advance

Upvotes: 0

Views: 765

Answers (2)

Poul Kruijt
Poul Kruijt

Reputation: 71891

const data = [{"code":"RRR","name":"Name","rate":"1.17","$key":"MeJy8ClJvJy"}];

The [] as you call them, depict it's an Array. So you should use array functions for these. A {} indicates a plain object.

If you want to see all the values in the array, you will get a list of objects like this:

data.forEach((item) => console.log(item));

This will log an item for every item in the array.


If you want to see the values of the properties of the objects in the array, you can do the following:

data.forEach((item) => console.log(Object.values(item)));

A small but crucial hint. I'm all for starting with TypeScript instead of plain JavaScript, but first solidify the basic concepts of the language in your head, before starting something as big as Angular.

Upvotes: 2

Javvy7
Javvy7

Reputation: 146

Spread operator should do it -

console.log(Object.values(...[{"code":"RRR","name":"Name","rate":"1.17","$key":"MeJy8ClJvJy"}]))

Upvotes: 0

Related Questions