Map Angular Array to Object - arrays

I have been looking and have found a few good references for transforming arrays to objects, but I can't seem to find my use case. I have an array with the following format
[
{id: 1, name: 'hello', display: false},
{id: 5, name: 'hello2', display: true},
{id: 7, name: 'hello8', display: true},
]
and I would like to map it into something like this
{
5: {id: 5, name: 'hello2'},
7: {id: 7, name: 'hello8'}
}
I have been trying to use the map function, but I can't figure it out since I want the keys of my map to be an id. This is what I have so far but it is obviously wrong.
const myArray = [
{id: 1, name: 'hello', display: false},
{id: 5, name: 'hello2', display: true},
{id: 7, name: 'hello8', display: true},
];
const myMap = myArray.filter(row => row.display)
.map(row => {
return {row.id: {id: row.id, name: row.name}
});

Filter the array, map it to pairs of [id, obj], and convert to an object using Object.fromEntries(). You can use destructuring and rest syntax (...) to remove display.
Notes: if Object.fromEntries() is not supported, change target in TS Config to ES2019.
const arr = [{id: 1, name: 'hello', display: false},{id: 5, name: 'hello2', display: true}, {id: 7, name: 'hello8', display: true}]
const result = Object.fromEntries(
arr.filter(o => o.display)
.map(({ display, ...o }) => [o.id, o])
)
console.log(result)
Another option is to use Array.reduce() to create the object. In that case, you can skip objects with false display.
const arr = [{id: 1, name: 'hello', display: false},{id: 5, name: 'hello2', display: true}, {id: 7, name: 'hello8', display: true}]
const result = arr.reduce((acc, { display, ...o }) => {
if(display) acc[o.id] = [o.id, o]
return acc
}, {})
console.log(result)

Related

How to Add Object to Array State in ReactJs?

I have this array of objects state, and it is working fine.
I need add another object to it dynamically.
const [productData, SetProductData] = useState({
sizes: [
{id: 2, value: 'Small', isActive: false},
{id: 2, value: 'Medium', isActive: false},
{id: 2, value: 'Large', isActive: true},
{id: 2, value: 'X Large', isActive: false},
{id: 2, value: 'XX Large', isActive: false}
]
})
I tried to do it like this, but it is not working
const addObjectToArray = obj => {
SetProductData(current => [...current, obj]);
};
addObjectToArray( {id: 3, value: 'XXX Large', isActive: true} )
I also need to update it dynamically
You need to keep the same structure in your state. You had an object, and you're changing it to an array. So
const addObjectToArray = obj => {
SetProductData(current => ({
...current,
sizes: [...current.sizes, obj]
}));
};
addObjectToArray( {id: 3, value: 'XXX Large', isActive: true} )

How to Manage the response of the API in react?

i did a request to the API, then the response is as the following:
data1 = [{id: 1, code:1, title:title1}, {id:2, code:3, title:title2}, ...]
Now i would like to extract an array of the titles of the above response as below:
titles = [title1, title2, ....]
how can i do it by map?
And the second question:
Consider if the response would be as follow:
data2 = [{id: 1, code:1, title:title1, chapters:[{id:1, chapter: chapter1},{id:2, chapter: chapter2}, ...]}, {id:4, code:5, title:title3, chapters:[{id:4, chapter: chapter3}, ...]}, ...]
In this case how can i extract an array of the chapters as following:
chapters = [chapter1, chapter2, chapter3]
I tried to do them as below:
for the first question:
title = data1.map((item) => {item.title})
for the second one i did:
chapters = data2.chapters.map((item) => {item.chapter})
But it doesn't work. I think some where there are error in syntaxes.
Can any one help me how to manage these data?
Thank you.
Yep, you are wrong with syntax.
Firs case - title = data1.map((item) => {item.title})
You've wrapped item.title with {}, so you should add return. Or omit {}.
For example: title = data1.map(item => item.title)
Second case - same issue with {}, but you should also use flatMap because you need flat list in result. If you write with regular map - you won't get desired ["chapter1", "chapter2"].
See also detailed example below.
const data1 = [
{ id: 1, code: 1, title: "title1" },
{ id: 2, code: 3, title: "title2" }
];
const data1_mapped = data1.map(d => d.title);
console.log(data1_mapped);
const data2 = [
{
id: 1,
code: 1,
title: "title1",
chapters: [{ id: 1, chapter: "chapter1" }, { id: 2, chapter: "chapter2" }]
},
{
id: 2,
code: 2,
title: "title2",
chapters: [{ id: 1, chapter: "chapter22" }, { id: 2, chapter: "chapter32" }]
}
];
const data2_mapped = data2.flatMap(d => d.chapters.map(c => c.chapter));
console.log(data2_mapped);
You are not returning a value. Try removing braces like so...
title = data1.map((item) => item.title)
chapters = data2.chapters.map((item) => item.chapter)
See this for more info on the issue:
Meaning of curly braces in array.map()

how to update setstate array of object values in react js

How can I update setChoices object values, Below is an example of my problem:
I m having choices array of object with values. on setstate(setChoices) want to update the object values.
let [choices, setChoices] = useState({
Choices: [
{
OneChoiceWithValueSelected: {
OptionSelected: '15518',
Price: 0.9,
Quantity: 1,
},
ProductOptionId: 5712,
},
],
Note: 'test message',
ProductId: 6,
Quantity: 1,
StoreId: '6',
TableId: 0,
});
const demo = () => {
setChoices({
Choices: [
{
OneChoiceWithValueSelected: {
OptionSelected: '15518',
Price: 100,
Quantity: 12,
},
ProductOptionId: 5712,
},
],
Note: 'its a new message',
ProductId: 6,
Quantity: 10,
StoreId: '10',
TableId: 0,
});
alert(JSON.stringify(choices));
};
return (
<div>
<button onClick={demo}>test</button>
</div>
);
According to you're state structure, you have to update the setChoices part as follows
const demo = () => {
setChoices({
Choices[0].OneChoiceWithValueSelected.OptionSelected: '15518',
Choices[0].OneChoiceWithValueSelected.Price: 100,
Choices[0].OneChoiceWithValueSelected.Quantity: 12,
Choices[0].ProductOptionId: 5712,
Note: 'its a new message',
ProductId: 6,
Quantity: 10,
StoreId: '10',
TableId: 0
})
alert(JSON.stringify(choices))
}
you have to access the 0th array element to update it's attributes, because the OneChoiceWithValueSelected object is the first element of the Choices array and then use object notation to access others.

How to filter multiple objects from a list objects by a property array?

I have a object array in which each object contain an id and a name and a separate array contains a set of ids. I want to filter first array based on the second array.
const data= [
{
id: 1,
name: 'name1'
},
{
id: 2,
name: 'name2'
},
{
id: 3,
name: 'name3'
},
{
id: 4,
name: 'name4'
}
];
const array = [1,3,4];
const expectedResult= [
{
id: 1,
name: 'name1'
},
{
id: 3,
name: 'name3'
},
{
id: 4,
name: 'name4'
}
];
Use .filter and .includes
const data= [
{
id: 1,
name: 'name1'
},
{
id: 2,
name: 'name2'
},
{
id: 3,
name: 'name3'
},
{
id: 4,
name: 'name4'
}
];
const array = [1, 3, 4]
const result = data.filter((item) => {
//gives us items that passes a condition
return array.includes(item.id)
})
console.log(result)

react-absolute-grid, displayObject issue

I am trying to use this component: https://github.com/jrowny/react-absolute-grid.
The documentation says I should pass a displayObject which renders items.
So I created a displayObject, like the one in the docs which has this render method:
render: function() {
// Supposing your item shape is something like {name: 'foo'}
const { item, index, itemsLength } = this.props;
return <div>Item {index} of {itemsLength}: {item.name}</div>;
}
I passed it to the component like this:
<AbsoluteGrid
items={SampleData.screens}
displayObject={<DisplayObject/>}
onMove={onMoveDebounced}
dragEnabled={true}
responsive={true}
verticalMargin={42}
itemWidth={250}
itemHeight={250}
filteredProp={'name'}
/>
Where SampleData.screens is:
module.exports = {
screens: [
{'url': 'http://invisionapp.com/subsystems/do_ui_kit/assets/img/screens/original-1x/screen-1-1-login.jpg', 'name': 'login', 'sort': 1, 'key': 1},
{'url': 'http://invisionapp.com/subsystems/do_ui_kit/assets/img/screens/original-1x/screen-1-2-sign-up.jpg', 'name': 'signup', 'sort': 2, 'key': 2},
{'url': 'http://invisionapp.com/subsystems/do_ui_kit/assets/img/screens/original-1x/screen-1-3-walkthrough.jpg', 'name': 'walkthrough', 'sort': 3, 'key': 3}
]
};
When I open the page in the browser, I don't see the text from the displayObject.
How can I use the displayObject?
DisplayObject works good when is a function that return the render html, I try creating a different React.Component for it but got some issues
const items = [
{ key: "0", sort: 0, name: 'Test 1', filtered: false },
{ key: "1", sort: 1 ,name: 'Test 2', filtered: false },
{ key: "2",sort: 2, name: 'Test 3', filtered: false},
{ key: "3", sort: 3,name: 'Test 4', filtered: false }
]
function GridItem(props) {
const { item, index, itemsLength } = props;
return <div >
<span>{item.name}</span>
</div>;
}
const AbsoluteGrid = createAbsoluteGrid(GridItem);

Resources