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?
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:
inputXX
, while others may have multiple such properties.inputN
will be stored at index N-1
in the resulting array, even if that means there will be gaps in the array.