Home > OS >  Receive value by key
Receive value by key

Time:07-29

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

CodePudding user response:

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.

CodePudding user response:

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)

CodePudding user response:

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"]);
  }
});

CodePudding user response:

Making an improvement to Vega's answer:

You can use the find function instead of the filter function as find returns only the first match and that's what you want it seems

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 element = txt.find(t => t.key === 'text')

console.log(element.value);
  • Related