Fonty
Fonty

Reputation: 159

cant iterate over JSON with typescript/javascript

I've got a JSON document with different field names (27_sourcename0, 27_sourcename1 ...). To check if the field name exists, I created a field name array (this.sourcenames27).

So I want to check if the field name exists to get the value "image.jpg".

this.document = { 
  _source: {
             ID: "55",
             27_sourcename0: "image.jpg"
             27_sourcename1: "image.jpg"
           }
}


this.sourcenames27 = [
      {
        sourceName: '27_sourcename0',
      },
      {
        sourceName: '27_sourcename1',
      },
      {
        sourceName: '27_sourcename2',
      },
]

//this doesnt work
for (let item of this.sourcenames27) {
console.log(this.document['_source'] + item.sourceName);
   if (this.document['_source'] + item.sourceName) {
      console.log('jeah it exists');
   }
}

// this works well
console.log(this.document['_source']['27_sourcename1']

I am getting the value when i use

this.document['_source']['27_sourcename1']

But I can't get the value when I iterate over the this.sourcenames27 array. What do I overlook here?

Expected Output: image.jpg, image.jpg

Upvotes: 0

Views: 36

Answers (1)

Raja Jaganathan
Raja Jaganathan

Reputation: 36197

Try to access like this.document['_source'][item.sourceName], not with + operator, you are try to do like {} + string type.

this.document = { 
    _source: {
        ID: "55",
        27_sourcename0: "image.jpg"
        27_sourcename1: "image.jpg"
    }
  }
    
  this.sourcenames27 = [
        {
          sourceName: '27_sourcename0',
        },
        {
          sourceName: '27_sourcename1',
        },
        {
          sourceName: '27_sourcename2',
        },
  ]
  
 
  for (let item of this.sourcenames27) {
    console.log(this.document['_source'][item.sourceName]); //Note here
     if (this.document['_source'][item.sourceName]) { // Note here
        console.log('jeah it exists');
     }
  }
  
  // this works well
  console.log(this.document['_source']['27_sourcename1']

Upvotes: 1

Related Questions