I want to filter out a nested array of objects but stuck at the filter part.
How to remove one of the mark?
this.state = {
data: [
{
id: 1,
name: "Main",
subs: [
{
id: "jay",
name: "Jay",
mark: [
{
id: "5a5d84b94a074c49ef2d4553",
name: 100
},
{
id: "5a5d84b94a074119ef2d4553",
name: 70
}
]
}
]
}
]
};
https://codesandbox.io/s/p39momxzp7
I try to use es6 as it's more readable.
expected output
data: [
{
id: 1,
name: "Main",
subs: [
{
id: "jay",
name: "Jay",
mark: [
{
id: "5a5d84b94a074119ef2d4553",
name: 70
}
]
}
]
}
]
Since there are multiple nested arrays in your data structure, you need to use forEach
those many times
data.forEach( s => //iterate data
s.subs.forEach( t => //iterate subs
( t.mark = t.mark.slice( 1, 2 ) ) ) ); //slice the second value out
Demo
var data = [{ id: 1, name: "Main", subs: [{ id: "jay", name: "Jay", mark: [{ id: "5a5d84b94a074c49ef2d4553", name: 100 }, { id: "5a5d84b94a074119ef2d4553", name: 70 } ] }] }]; data.forEach(s => s.subs.forEach(t => (t.mark = t.mark.slice(1,2)))); console.log(JSON.stringify(data, 0, 4))
In case the last value should be picked ?
data.forEach( s => //iterate data
s.subs.forEach( t => //iterate subs
( t.mark = t.mark.slice( -1 ) ) ) ); //slice the last value out
If you are trying to filter a relevant mark
by a given id
,
you can combine Array#map
and Array#filter
to achieve it:
Note that i'm also using the Object Rest/Spread Properties proposal (stage 4)
Running example
const state = { data: [{ id: 1, name: "Main", subs: [{ id: "jay", name: "Jay", mark: [{ id: "5a5d84b94a074c49ef2d4553", name: 100 }, { id: "5a5d84b94a074119ef2d4553", name: 70 }] }] }] }; const mark_id = '5a5d84b94a074119ef2d4553'; const nextState = { ...state, data: state.data.map(obj => { const filteredSubs = obj.subs.map(sub => { const markById = sub.mark.filter(m => m.id === mark_id); return { ...sub, mark: markById } }); return { ...obj, subs: filteredSubs } }) }; console.log(nextState);
You can even use lodash which contains many methods that can be handled easily.
Check if this is what you are looking for. (there is a good scope to refactor it but before that would like to understand if thats what you are looking for)
Below is the code that has been used there.
let inputId = "5a5d84b94a074c49ef2d4553";
let filteredData =_.each(_.cloneDeep(data), function(value, key1) {
_.each(value.subs, function(valueSubs, key2) {
var finalSubMark = _.find(valueSubs.mark, function(eachMark) {
return eachMark.id == inputId;
});
_.set(valueSubs, "mark", finalSubMark);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.