Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
Find elements from concatenate strings in JS

How can I search the values in an Object from strings, something like:

const query = "['arg1']['arg2']"

const renderImage = async (index) => {

    const data = await fetchImage(index)
    const image = document.querySelector('.div')
    
    image.setAttribute("src", data`${query}`)

}

The fetch function is perfect working.

Edit:

The image source is in the data['arg1']['arg2']. If I use image.setAttribute("src", data['arg1']['arg2']) the code runs fine, but I need to do this dynamically and concatenate strings will help me.

Summing up: can I get the same result data['arg1']['arg2'] concatenating object and "query" (['arg1']['arg2'])?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

you can store the path as an array of keys and access it like this

const query = ['arg1', 'arg2']
...
    image.setAttribute("src", query.reduce((o, k)=>o[k], data))

about 4 years ago · Juan Pablo Isaza Report

0

It seems you are trying to extract the property names you want, from a poorly formatted string. Ideally, you would get query into a better format to begin with, so you don't have to parse the string. For instance, if you could get query as two separate variables:

const query1 = 'arg1';
const query2 = 'arg2';
image.setAttribute("src", data[query1][query2]);

you could also store query in a better data type to do this, like const query = { arg1: 'arg1', arg2: 'arg2' }; then access with dot syntax data[query.arg1][query.arg2].

But if you must keep query as this weirdly formatted string for some reason, you can do something like this, parsing the string into it's parts, putting them into an array, then using the array to access the right data within data.

let query = "['arg1']['arg2']";
query = query.slice( 2 ).slice( 0, -2 ).split( "']['" );
image.setAttribute( "src", data[query[0]][query[1]] );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!