Search code examples
javascriptarraysoptional-chaining

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

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

So for above sample code : I want output to be ["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?


Solution

  • 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.
    • Allows that some objects in the input array have no properties that match the pattern inputXX, while others may have multiple such properties.
    • 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.