prem89 prem89 - 1 month ago 8
Javascript Question

Get the latest occurence of object value

I have a JSON array as follows

[{
"x": {
"id": "123"
},
"y": {
"value": "123"
}
}, {
"x": {
"id": "256"
},
"y": {
"value": "256"
}
}, {
"y": {
"value": "789"
}
}]


How do i get the latest
id
value of object
x
and a array with all values of object
y
. So the output should be
256
&
[123, 256, 789]

Answer

You could map the value and check for a given id and use it as last value for x.

var data = [{ x: { id: "123" }, y: { value: "123" } }, { x: { id: "256" }, y: { value: "256" } }, { y: { value: "789" } }],
    lastX,
    allY = data.map(function (a) {
        if (a.x && 'id' in a.x) {
            lastX = a.x.id;
        }
        return a.y.value;
    });

console.log(lastX);
console.log(allY);

Comments