简体   繁体   English

动态字符串的可选链接作为 JS 中的属性

[英]Optional chaining for dynamic strings as property in JS

I have following sample code:我有以下示例代码:

var x = [
{input1: "aaa"},
{input2: "bbb"},
{input444: "ddd"},
{input55: "eee"}
{input3: "ccc"},
]

I am trying to get values of props which if exists in the object something like我正在尝试获取 object 中存在的道具值,例如

x.forEach((item, index) => {
 console.log(item.[`input${index}`]);
})

So for above sample code: I want output to be ["aaa", "bbb", "ccc"]所以对于上面的示例代码:我希望 output 是 ["aaa", "bbb", "ccc"]

I know the first part of the property (which in this example is 'input') and second part will be index only我知道属性的第一部分(在本例中为“输入”),第二部分将仅为索引

Is it possible to know the values using Optional chaining?是否可以使用可选链接知道值? What I am missing?我错过了什么?

You need just to add one to index and take bracket notation for the object without dot.您只需在索引中添加一个并为不带点的 object 采用括号表示法。

The optional chaining operator ?. 可选的链接运算符?. works only for having undefined source value.仅适用于具有undefined的源值。 It does not switch some program logic for either showing a value or not.它不会切换某些程序逻辑以显示或不显示值。 In this case, you could check if the property exists in the object and then show th wanted part without some optional chaining在这种情况下,您可以检查 object 中是否存在该属性,然后在没有一些可选链接的情况下显示想要的部分

 var x = [{ input1: "aaa" }, { input2: "bbb" }, { input3: "ccc" }, { input444: "ddd" }, { input55: "eee" }]; x.forEach((item, index) => { if (`input${index + 1}` in item) console.log(item[`input${index + 1}`]); });

Optional chaining makes little sense unless you are only looking for a specific property.除非您只是在寻找特定的属性,否则可选链接几乎没有意义。 Use Object.values or Object.entries .使用Object.valuesObject.entries

 var x = [ {input1: "aaa"}, {input2: "bbb"}, {input3: "ccc"}, {input4: "ddd"}, {input5: "eee"} ] x.forEach((item, index) => { console.log(Object.values(item)); console.log(Object.values(item)[0]); // If it is just one, reference it })

If it has to match only if the index matches than it still does not require optional chaining to read the value.如果它只有在索引匹配时才匹配,那么它仍然不需要可选链接来读取值。

 var x = [ {input1: "aaa"}, {input2: "bbb"}, {input3: "ccc"}, {input4: "ddd"}, {input555: "eee"} ] x.forEach((item, index) => { console.log(item[`input${index+1}`]); })

And after your 5th or so edit, to get the output you want is even weirder.... You would need to use reduce OR map and filter.在你的第 5 次左右编辑之后,要获得你想要的 output 就更奇怪了......你需要使用 reduce OR map 和过滤器。 You need to keep track of the current index.您需要跟踪当前索引。

 const x = [ {input1: "aaa"}, {input2: "bbb"}, {input444: "ddd"}, {input55: "eee"}, {input3: "ccc"}, ]; let current = 1; const out = x.reduce(function (acc, obj) { const key = `input${current}`; if(obj.hasOwnProperty(key)){ acc.push(obj[key]); current++; } return acc; }, []); console.log(out);

Since the order of the input is not guaranteed, I would do this:由于不能保证输入的顺序,我会这样做:

 var x = [{input1: "aaa"}, {input2: "bbb"},{input444: "ddd"},{input55: "eee"},{input3: "ccc"},]; let result = Object.assign([], ...x.flatMap(o => Object.entries(o).filter(([k]) => k.startsWith('input') && +k.slice(5) >= 1 && +k.slice(5) <= x.length ).map(([k, v]) => ({ [k.slice(5)-1]: v }) ) )); console.log(result);

Some characteristics of this solution:该解决方案的一些特点:

  • Requires that the suffix in the property name lies between 1 and the length of the input array.要求属性名称中的后缀介于 1 和输入数组的长度之间。
  • Allows that some objects in the input array have no properties that match the pattern inputXX , while others may have multiple such properties.允许输入数组中的某些对象没有与模式inputXX匹配的属性,而其他对象可能具有多个此类属性。
  • A value that is assigned to a property inputN will be stored at index N-1 in the resulting array, even if that means there will be gaps in the array.分配给属性inputN的值将存储在结果数组的索引N-1处,即使这意味着数组中会有间隙。

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

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