Quantity update in cartReducer updates ItemReducer's item's quantity in ReactJs - javascript

I have two reducers ItemReducer where I am setting initially all the items which I am fetching using Axios calling GET API. Another reducer is CartReducer where I am storing cartItems.
ItemReducer
{
item_id: '1',
category_id: '12',
item_name: 'Churros',
item_image: 'item_081220170230.jpg',
is_variant: '2',
item_price: '9',
currency_code: 'USD',
currency_symbol: '$',
item_quantity: '1',
is_type: 'item'
}
CartReducer
{
item_id: '1',
category_id: '12',
item_name: 'Churros',
item_image: 'item_081220170230.jpg',
is_variant: '2',
item_price: '9',
currency_code: 'USD',
currency_symbol: '$',
item_quantity: '1',
is_type: 'item'
}
The problem is whenever I try to update current cart item's quantity it updates itemReducer item's quantity also I tried to use an index for catching exact item but not worked for me.
Here is the code.
const qtyChange = (item_id, variation_id) => {
if (cartReducer.items){
const {items} = cartReducer;
if ( item_id && !variation_id ) {
const filteredItem = items.filter(item => item.item_id === item_id).pop();
filteredItem.item_quantity = Number( filteredItem.item_quantity ) + 1;
} else{
const filteredItem = items.filter(item => item.item_id === item_id && item.variation_id === variation_id).pop();
filteredItem.item_quantity = Number ( filteredItem.item_quantity ) + 1;
}
}
};

Related

Lodash - Merge object from another array with same key as sub object to main array

const _ = require('lodash');
const parentDetails = [
{
'name': '5003',
'id': '1'
},
{
'name': '5000',
'id': '2'
}
];
const childrenDetails = [
{
'cid': '11',
'Reference': '5003'
},
{
'cid': '22',
'Reference': '5000'
}
];
Desired Output using lodash library: Extract matching reference from the second array with the name of the first array and append the matching child detail as an object to the first array as shown below. The result should not mutate the original array.
result = [
{
'name': '5003',
'id': '1',
'childrenDetail' : {
'cid': '11',
'Reference': '5003'
}
},
{
'name': '5000',
'id': '2',
'childrenDetail' : {
'cid': '22',
'Reference': '5000'
}
}
];
Here is an example using _.find()
const result = parentDetails.map(elm => {
const childrenDetail = _.find(childrenDetails, elm2 => elm2.Reference === elm.name);
if (childrenDetail) return ({...elm, childrenDetail});
});
console.log(result);
You can also replace array.map() with _.map().

Loop over object to run an axios query

I need to be able to execute await axios.post (api, data)
taking all the values of parameters
const parameters = {
userId: [ '2', '4' ],
categoryId: '2'
}
that is, all possible combinations: userId=2&categoryId=2 y userId=4&categoryId=2
What I have:
const data = {};
const api = url_api + "?" + "userId=" + userId + "&categoryId =" + categoryId;
const resp = await axios.post(api, data);
How can I do it?
And how would it be for the cases that parameters is:
const parameters = {
userId: [ '2', '4' ],
categoryId: [ '1', '6' ]
}
all possible combinations: userId=2&categoryId=1, userId=2&categoryId=6, userId=4&categoryId=1, userId=4&categoryId=6
Thanks!
I think you should use inner & outer loop for it.
if your data is like this, do below.
const parameters = {
userId: [ '2', '4' ],
categoryId: [ '1', '6' ]
};
const dataList = [];
parameters.userId.forEach(u => {
parameters.categoryId.forEach(c => {
dataList.push(`${url_api}?userId=${u}&categoryId=${c}`);
})
});
dataList.forEach(async(d) => {
const res = await axios.post(d, data);
...
});
and if your data can be like this, do below.
const parameters = {
userId: [ '2', '4' ],
categoryId: '3',
};
const dataList = [];
parameters.userId.forEach((u) => {
parameters.categoryId.length <= 1
? dataList.push(`${url_api}?userId=${u}&categoryId=${parameters.categoryId}`)
: parameters.categoryId.forEach((c) => {
dataList.push(`${url_api}?userId=${u}&categoryId=${c}`);
});
});
dataList.forEach(async(d) => {
const res = await axios.post(d, data);
...
});

Retrieving item between two arrays of object with complex conditions

I got two lists of objects :
let list1 = [{id: '1', status: 'use', comment: 'xxxx'}, {id: '2', status: 'ready', comment: 'yyyy'}, {id: '3', status: 'ready', comment: 'zzzz'}];
let list2 = [{uid: '1', elec: 60}, {uid: '2', elec: 60}, {uid: '10', elec: 60}, {uid: '3', elec: 40}];
What i want is to retrieve an object of list2 that have elec > 50 and the same uid than one item id of the list1 only if the item of the list1 have a status == "ready". Also, i want to add to this item the parameter 'comment' from the object of the list1.
In this exemple, my result value would be : {uid: '2', elect: 60, comment: 'yyyy'}.
I did this :
let list1Filtered = list1.filter(itemList1 => itemList1.status == 'ready');
let list2Filtered = list2.filter(itemList2 => itemList2.elec > 50);
var result;
for ( let itemList1Filtered of list1Filtered ) {
for ( let itemList2Filtered of list2Filtered ) {
if (!result && itemList1Filtered.id == itemList2Filtered.uid) {
result = itemList2Filtered;
result.comment = itemList1Filtered.comment;
}
}
}
return result;
I want to know if there is a more elegant and/or more sophisticated way to do this in Javascript.
You could collect wanted comments from list1 and reduce list2 with a check for the value of elec and if an item exist from the other list. Then return a new object.
This approach needs only two loops.
const
list1 = [{ id: '1', status: 'use', comment: 'xxxx' }, { id: '2', status: 'ready', comment: 'yyyy' }, { id: '3', status: 'ready', comment: 'zzzz' }],
list2 = [{ uid: '1', elec: 60 }, { uid: '2', elec: 60 }, { uid: '10', elec: 60 }, { uid: '3', elec: 40 }],
l1 = list1.reduce((r, { id, status, comment }) => {
if (status === 'ready') r[id] = { comment };
return r;
}, {}),
result = list2.reduce((r, o) => {
if (o.elec > 50 && o.uid in l1) r.push({ ...o, ...l1[o.uid]})
return r;
}, []);
console.log(result);
let result = {
...list2.filter(
a => a.elec > 50 && a.uid === list1.filter(b => b.status === "ready")[0].id)[0],
comments: list1.filter(b => b.status === "ready")[0].comment
}
Try this:
let list1 = [
{ id: '1', status: 'use', comment: 'xxxx' },
{ id: '2', status: 'ready', comment: 'yyyy' },
{ id: '3', status: 'ready', comment: 'zzzz' },
];
let list2 = [
{ uid: '1', elec: 60 },
{ uid: '2', elec: 60 },
{ uid: '10', elec: 60 },
{ uid: '3', elec: 40 },
];
let result = null;
let itemFound;
const filteredList = list2.filter((list2Item) => {
if (!result) {
itemFound =
list2Item.elec > 50 &&
list1.find(
(list1Item) =>
list2Item.uid === list1Item.id && list1Item.status === 'ready'
);
if (itemFound) {
result = {
uid: list2Item.uid,
elect: list2Item.elec,
comment: itemFound.comment,
};
}
}
});
console.log(result);
This should do the job:
const list1 = [{
id: '1',
status: 'use',
comment: 'xxxx'
}, {
id: '2',
status: 'ready',
comment: 'yyyy'
}, {
id: '3',
status: 'ready',
comment: 'zzzz'
}];
const list2 = [{
uid: '1',
elec: 60
}, {
uid: '2',
elec: 60
}, {
uid: '10',
elec: 60
}, {
uid: '3',
elec: 40
}];
const filteredList = list2.filter(item => {
const readyItemsList1 = list1.filter(item => item.status === 'ready').map(item => item.id);
return item.elec > 50 && readyItemsList1.indexOf(item.uid) > -1
}).map(item => {
const comment = list1.find(it => it.id === item.uid).comment;
item.comment = comment;
return item;
});
console.log(filteredList);
you can restructure your data. List1 convert it in object. And now we can find solution in O(n).
let list1 = [{
id: '1',
status: 'use',
comment: 'xxxx'
}, {
id: '2',
status: 'ready',
comment: 'yyyy'
}, {
id: '3',
status: 'ready',
comment: 'zzzz'
}];
let list2 = [{
uid: '1',
elec: 60
}, {
uid: '2',
elec: 60
}, {
uid: '10',
elec: 60
}, {
uid: '3',
elec: 40
}];
const itemList = {}
list1.forEach(item => {
if (item.status === 'ready') {
itemList[item.id] = item.comment
}
});
const result = list2.filter(item => itemList[item.uid] && item.elec > 50).map(item => {
item['comment'] = itemList[item.uid]
return item
})
console.log(result)
filter and map will help you.
filter can select items fit some criteria, and map let you change the data to pick.
For list1, select item with status equals 'ready', then take only id.
var ready_id_array = list1.filter(item=>item.status == 'ready').map(item=>item.id);
For list2, check item that its uid contained in ready_id_array, and elec larger than 50.
var result = list2 .filter(item => ready_id_array.indexOf(item.uid) > -1 && item.elec > 50);
to append the comment, a dictionary is created and then put comment back to result
var comment_dictionary = list1.reduce((a,x) => ({...a, [x.id]: x.comment}), {});
result.forEach(item => item.comment = comment_dictionary[item.uid]);
and you will have the result.
[{uid: "2", elec: 60, comment: "yyyy"}]

Filtering array of objects if specific key contains search term

I am trying to filter through an object with multiple key/value pairs by a specific key. It appears that the code I've written is searching the entire object regardless of the key...
If key name contains the search term, return the search term.
Array of Objects:
export const someArrayOfObjects = [
{ id: '1', name: 'Something' },
{ id: '2', name: 'Another' },
{ id: '3', name: 'Lets do one more' },
]
Search:
const searchResults = someArrayOfObjects.filter((o) =>
Object.keys(o).some((k) => o[k].toString().toLowerCase().includes(searchTerm.toLowerCase()))
);
So if I search "Something", I only want it to loop through name to search for that term...
You don't need the Object.keys loop.
const someArrayOfObjects = [
{ id: '1', name: 'Something' },
{ id: '2', name: 'Another' },
{ id: '3', name: 'Lets do one more' },
];
let key = 'name';
let searchTerm = 'th';
const res = someArrayOfObjects.filter(o =>
o[key].toLowerCase().includes(searchTerm.toLowerCase()));
console.log(res);
similar to iota's, you don't need to create the extra array with Object.keys.
just loop/check every item inside the original array with the 'name' key.
you can also try to make it more reusable like below.
const someArrayOfObjects = [
{ id: '1', name: 'Something' },
{ id: '2', name: 'Another' },
{ id: '3', name: 'Lets do one more' },
];
const search = function (anyArray, searchTerm) {
return anyArray.filter((obj) => {
if (obj.name === searchTerm) {
return obj.name;
}
return false;
});
};
const case1 = search(someArrayOfObjects, 'Something');
console.log(case1);

Find object in array ids

I've list of id's in array and list of article in other array.
I would like filter my article array by ids find in id's array.
Exemple :
const ids = [ '1', '2', '3' ];
const articles = [
{ id: '1', title: 'blua' },
{ id: '10', title: 'blua' }
...
];
I've try this :
ids.map((id) => {
return audits.find((audit) => {
return id === audit.id;
});
});
But return underfined :/
I think it's not a good methode ^^
Anyone can help me ?
Thank you !
Use array.prototype.filter and array.prototype.includes:
const ids = [ '1', '2', '3' ];
const articles = [ { id: '1', title: 'blua' },{ id: '10', title: 'blua' } ];
const filtered = articles.filter(a => ids.includes(a.id));
console.log(filtered);
const ids = [ '1', '2', '3' ];
const articles = [
{ id: '1', title: 'blua' },
{ id: '10', title: 'blua' }
...
];
let results = articles.filter( (a) => ids.indexOf(a.id) !== -1);

Categories

Resources