How can I change TS object array format? - arrays

Array which I want change
I have got this array in TypeScript, I want it change as bellow.
list = [{id : 1, name : bus, active : 1}, {id : 2, name : car}]
Can anyone help me?

You can map the input and reduce each element to an object.
const list = [
[{ id: 1 }, { name: 'bus' }, { active: 1 }],
[{ id: 2 }, { name: 'car' }],
];
const result = list.map((el) => {
return el.reduce((acc, curr) => {
return { ...acc, ...curr };
}, {});
});
console.log(result);

Related

Update objects in an array inside map Function React or React-Hooks or React-Native

it is deleting all objects except last one from the array instead of updating a property of all objects, want to update 'ItemDeliveryStatus' of all objects inside map function
const [arrayList, setArrayList] = useState([
{ Id: 1, Name:'A', ItemDeliveryStatus:1 },
{ Id: 2, Name:'B', ItemDeliveryStatus:1 },
{ Id: 3, Name:'C', ItemDeliveryStatus:1 },
{ Id: 4, Name:'D', ItemDeliveryStatus:1 },
])
const [returnCount, setReturnCount ]=useState(0)
const updateAllObjects=()=>
{
arrayList.map(items=>
{
if(items.ItemDeliveryStatus==1)
{
setArrayList([{ ...items, ItemDeliveryStatus:4}])
}
if (items.ItemDeliveryStatus==4)
{
setReturnCount(prev=>prev+1)
}
})
}
final Result Should be like this
([
{ Id: 1, Name:'A', ItemDeliveryStatus:4 },
{ Id: 2, Name:'B', ItemDeliveryStatus:4 },
{ Id: 3, Name:'C', ItemDeliveryStatus:4 },
{ Id: 4, Name:'D', ItemDeliveryStatus:4 },
])
You can update like this for all object:
const updateAllObjects = (value) => {
setArrayList(
arrayList.map((item) => {
if (item.ItemDeliveryStatus == 1) {
return { ...item, ItemDeliveryStatus: value };
};
return item;
})
);
};

Update a selected property from react state of objects with arrays

Assume that this state has initial data like this
const [options, setOptions] = useState({
ProcessType: [
{ value: 1, label: 'Type1' }, { value: 2, label: 'Type2' }
],
ResponsibleUser: [
{ value: 1, label: 'User1' }, { value: 2, label: 'User2' }
]
});
The following function will be called again and again when a post/put called
Help me to complete the commented area as described there.
const fetchProcesses = async () => {
await axios.get(`${process.env.REACT_APP_SERVER_BASE_URL}/processes/`)
.then((result) => {
/*
I want here to clear the existing data in options.ProcessType and
map result.data as { value: result.data.id , label: result.data.name },....
and push/concat it into to options.ProcessType but i want to keep the data
inside options.ResponsibleUser unchanged.
result.data is an array of objects like this,
[
{ id: 1 , name: 'Type1', desc : 'desc1', creator: 3, status: 'active' },
{ id: 2 , name: 'Type2', desc : 'desc2', creator: 6, status: 'closed' },
.....
.....
]
*/
})
}
Here is a solution
const fetchProcesses = async () => {
await axios.get(`${process.env.REACT_APP_SERVER_BASE_URL}/processes/`)
.then((result) => {
// solution
setOptions({ResponsibleUser: [...options.ResponsibleUser], ProcessType: result.data.map(row => ({value: row.id, label: row.name}))})
})
}

how do i filter a array of objects to display only ids of the ones that have all existing type properties

im getting data from an API that looks like this:
const flags = [
{
type: "manyCards",
id: 1
},
{
type: "manyCards",
id: 2
},
{
type: ":premiumCard",
id: 1
},
]
i want to filter/sort it so it displays only the ids that have all types eg. id:1 has both manyCards and premiumCard.
som my result would be result = [1] in this case.
Cant figure out what Array prototypes to use.
To do this, I would group the initial data by id, so that we can know how many types each id has.
Once this is done, we can filter with any conditions we want.
const flags = [
{
type: "manyCards",
id: 1
},
{
type: "manyCards",
id: 2
},
{
type: ":premiumCard",
id: 1
},
{
type: "manyCards",
id: 3
},
{
type: "manyCards",
id: 2
},
{
type: ":premiumCard",
id: 3
},
]
let grouped = flags.reduce(function (r, a) {
r[a.id] = r[a.id] || []
r[a.id].push(a.type)
return r
}, {})
let result = Object.keys(grouped).filter(elem => (grouped[elem].includes("manyCards") && grouped[elem].includes(":premiumCard")))
console.log(result)

Filter Array based on a property in the array of its objects

Given is following data structure
const list = [
{
title: 'Section One',
data: [
{
title: 'Ay',
},
{
title: 'Bx',
},
{
title: 'By',
},
{
title: 'Cx',
},
],
},
{
title: 'Section Two',
data: [
{
title: 'Ay',
},
{
title: 'Bx',
},
{
title: 'By',
},
{
title: 'Cx',
},
],
},
];
What i want to do ist to filter this list based on title property in the data array of each object.
An example would be to have the list where the title property of the childs starts with "B", so the list will look like that:
const filteredList = [
{
title: 'Section One',
data: [
{
title: 'Bx',
},
{
title: 'By',
}
],
},
{
title: 'Section Two',
data: [
{
title: 'Bx',
},
{
title: 'By',
}
],
},
];
What i tried so far was something like that:
const items = list.filter(item =>
item.data.find(x => x.title.startsWith('A')),
);
or
const filtered = list.filter(childList => {
childList.data.filter(item => {
if (item.title.startsWith('B')) {
return item;
}
return childList;
});
});
But i think i am missing a major point here, maybe some of you could give me a tip or hint what i am doing wrong
Best regards
Your issue is that you're doing .filter() on list. This will either keep or remove your objects in list. However, in your case, you want to keep all objects in list and instead map them to a new object. To do this you can use .map(). This way you can map your objects in your list array to new objects which contain filtered data arrays. Here's an example of how you might do it:
const list=[{title:"Section One",data:[{title:"Ay"},{title:"Bx"},{title:"By"},{title:"Cx"}]},{title:"Section Two",data:[{title:"Ay"},{title:"Bx"},{title:"By"},{title:"Cx"}]}];
const filterByTitle = (search, arr) =>
arr.map(
({data, ...rest}) => ({
...rest,
data: data.filter(({title}) => title.startsWith(search))
})
);
console.log(filterByTitle('B', list));

Filter an Array based on multiple values

I have the following simple JSON array:
const personList = [
{
id: 1,
name: "Phil"
},
{
id: 2,
name: "Bren"
},
{
id: 3,
name: "Francis Underwood"
},
{
id: 4,
name: "Claire Underwood"
},
{
id: 5,
name: "Ricky Underwood"
},
{
id: 6,
name: "Leo Boykewich"
}
];
And I would like to filter this by passing an array of ids so something like [1,4] would be passed in and it would only return "Phill" and "Claire Underwood"
This is what the function looks like but I know it's wrong attendeeIds is an array that's passed in [1, 4]:
getAttendeesForEvent: (attendeeIds) => {
if (attendeeIds === undefined) return Promise.reject("No attendee id provided");
return Promise.resolve(personList.filter(x => x.id == [attendeeIds]).shift());
}
I haven't used JS in years. I've looked for examples but they all seem too complex for what I'm trying to achieve. So how can I filter this based on an array of id's passed in?
return Promise.resolve(personList.filter(x => attendeeIds.indexOf(x.id) !== -1));
You want to check if the id of each item your looping over exists inside of attendeeIds. Use Array.indexOf inside of the filter to do that.
This will return an array of { id: #, name: String } objects.
If you want to return just the names of those objects, you can do a map afterwards which will transform an array into another array using the function that you provide.
const filteredNames = personList
.filter(x => attendeeIds.indexOf(x.id) !== -1)
.map(x => x.name);
// ['Phil', 'Claire Underwood']
You could do something in these lines. Hope this helps.
const personList = [{
id: 1,
name: "Phil"
}, {
id: 2,
name: "Bren"
}, {
id: 3,
name: "Francis Underwood"
}, {
id: 4,
name: "Claire Underwood"
}, {
id: 5,
name: "Ricky Underwood"
}, {
id: 6,
name: "Leo Boykewich"
}];
let attendeeIds = [1, 5];
let getAttendeesForEvent = () => {
return new Promise(function(resolve, reject) {
if (attendeeIds === undefined) {
reject("No attendee id provided");
} else {
resolve(personList.filter((x) => attendeeIds.includes(x.id)).map((obj) => obj.name));
}
});
}
getAttendeesForEvent().then((data) => console.log(data))

Resources