0

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

3
  • 1
    this.document['_source'] resolves to an object, that has three keys in in. Performing a + against an object doesn't make sense. You have to do the [variable] access if you are trying to dynamically access a property off of an object. The fact that you are iterating isn't the main issue here. It is you are misunderstanding object access in the form that is not working Commented Nov 25, 2020 at 15:08
  • 1
    this.document['_source'][item.sourceName] Commented Nov 25, 2020 at 15:09
  • 1
    Does this answer your question? How can I access and process nested objects, arrays or JSON? Commented Nov 25, 2020 at 15:10

1 Answer 1

1

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.