0
votes

How could I get from the value of key:text. The problem is that txt[key].key gives an error

Element implicitly has an 'any' type because index expression is not of type 'number'.

What is the best option to get the value of key === text

const txt = [
  { key: 'topic', type: 'STRING', value: 'test' },
  { key: 'key', type: 'STRING', value: '007' },
  {
    key: 'text',
    type: 'STRING',
    value: 'I want to get this text'
  }
]

Object.keys(txt).forEach(key => {
    if (txt[key].key === 'text') {
        console.log("Found.");
    }
});

// What I also tried

Object.keys(txt).forEach((key: string | number) => {
    if (txt[key].key === 'text') {
        console.log("Found.");
    }
});

What I want

I want to get this text
3
Did you define the type of this object anywhere? - Kokodoko
@Kokodoko I do not think so. - Pyyyyt
There is a better way probably to do, but this should work: console.log(txt.filter(item => item?.key == "text").flatMap(item => item.value)) - Vega

3 Answers

1
votes

Why do you define your key as "string | number"? It is only string, isn't it ? But there is also another approach to your problem. You can simply use JavaScript filter() function.

const txt = [{
    key: 'topic',
    type: 'STRING',
    value: 'test'
  },
  {
    key: 'key',
    type: 'STRING',
    value: '007'
  },
  {
    key: 'text',
    type: 'STRING',
    value: 'I want to get this text'
  }
]

const textArray = txt.filter(t => t.key === 'text')

console.log(textArray);

Hope this will help you.

0
votes

This is not about types, this is how you access the item value.

The correct ways could be

console.log(txt.filter(item => item?.key == "text")[0].value)
0
votes

The other answers utilize filter method, below is the version using txt.forEach()

const txt = [
  { key: 'topic', type: 'STRING', value: 'test' },
  { key: 'key', type: 'STRING', value: '007' },
  {
    key: 'text',
    type: 'STRING',
    value: 'I want to get this text'
  }
]

txt.forEach(element => {
  if(element["key"] === "text")
  {
    console.log(element["value"]);
  }
});