简体   繁体   中英

JavaScript - Unable to get property from an Array of Object over function(parameters)

I have an Array of Objects:

var keywordset = [
    {word:["PO","Pending Order"],message:["Do you need to post registry?"]},
    {word:["delete"],message:["Do you want to delete in system?"]},
    {word:["contact"],message:["Inter-related feature: Contact Management"]}
]

Also, I created a function to convert the strings in an array of objects to UpperCase:

function ObjectArrayUpperCase(arrayname,array1){
console.log(arrayname[0])
console.log(array1)
for(b=0;b<arrayname.length;b++){
    for(c=0;c<arrayname[b].array1.length;c++){
        arrayname[b].array1[c] = arrayname[b].array1[c].toUpperCase()
      }
    }
}

Then, i run the ObjectArrayUpperCase() function by passing parameter into it

ObjectArrayUpperCase(keywordset,'word')

Unfortunately, the ObjectArrayUpperCase() function unable to process "array1" part, seems like unable to recognize it. But the "arrayname" working as expected, because if i replace "array1" to "word", the function work.

I tried to change the parameter but still no luck:

ObjectArrayUpperCase(keywordset,'word')
ObjectArrayUpperCase(keywordset,word)
ObjectArrayUpperCase(keywordset,keywordset.word)
etc...

Please advise how to pass the correct parameter to the function

You need square brackets to evaluate an expression like array1 to be used as the property name.

for(var b=0;b<arrayname.length;b++) {
    // -----------------------v------v--- and likewise below
    for(var c=0;c<arrayname[b][array1].length;c++){
        arrayname[b][array1][c] = arrayname[b][array1][c].toUpperCase()
      }
    }
}

Otherwise, how could it know if you meant to use the variable or an actual property with that name?

Also, be sure to declare your variables explicitly. I used var above.

Lastly, the loops can be written a little more cleanly using modern syntax and methods like this:

arrayname.forEach(obj => obj[array1] = obj[array1].map(s => s.toUpperCase()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM