动态字符串的可选链接,如 JS 中的 属性

Optional chaining for dynamic strings as property in JS

我有以下示例代码:

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

我正在尝试获取 props 的值,如果对象中存在类似

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

所以对于上面的示例代码:我希望输出为 ["aaa", "bbb", "ccc"]

我知道 属性 的第一部分(在这个例子中是 'input'),第二部分只是索引

是否可以使用可选链接知道值?我缺少什么?

索引加1,不带点的对象用括号表示。

optional chaining operator ?. 仅适用于具有 undefined 源值。它不会为了显示或不显示值而切换某些程序逻辑。在这种情况下,您可以检查 属性 是否存在于对象中,然后在没有一些可选链接的情况下显示想要的部分

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}`]);
});

可选链接没有什么意义,除非您只是在寻找特定的 属性。使用 Object.values or Object.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
})

如果仅当索引匹配时才必须匹配,那么它仍然不需要可选链接来读取值。

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

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

在您进行了大约 5 次编辑之后,要获得您想要的输出就更奇怪了....您需要使用 reduce OR map 和 filter。您需要跟踪当前索引。

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

由于不能保证输入的顺序,我会这样做:

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

此解决方案的一些特点:

  • 要求 属性 名称中的后缀介于 1 和输入数组的长度之间。
  • 允许输入数组中的某些对象没有匹配模式 inputXX 的属性,而其他对象可能有多个此类属性。
  • 分配给 属性 inputN 的值将存储在结果数组的索引 N-1 处,即使这意味着数组中会有间隙。