简体   繁体   English

JavaScript - 无法通过函数(参数)从对象数组中获取属性

[英]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()函数

ObjectArrayUpperCase(keywordset,'word')

Unfortunately, the ObjectArrayUpperCase() function unable to process "array1" part, seems like unable to recognize it.不幸的是, ObjectArrayUpperCase()函数无法处理“array1”部分,似乎无法识别它。 But the "arrayname" working as expected, because if i replace "array1" to "word", the function work.但是“arrayname”按预期工作,因为如果我将“array1”替换为“word”,该函数将起作用。

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.您需要方括号来评估像array1这样用作属性名称的表达式。

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.我在上面使用了var

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()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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