Javascript Object is pushing on both indexes rather than specific index - javascript

I searched this a lot on stackoverflow before posting this ticket so please don't consider this as duplicate question.
I have scenario of an array with two items, I am pushing an object at index 1 but it's pushing same object on both indexes.
Extra Object
const extraObj = {
"item_id": "4",
"item_name": "Extra Patty",
"item_image": "placeholder_img.jpg",
"item_price": "3.00",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "extra"
};
Items Array
const itemsArr = [
{
"item_id": "3",
"category_id": "12",
"item_name": "Waffles",
"item_image": "item_081220170335.jpg",
"is_variant": "0",
"item_price": "7",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "item"
},
{
"item_id": "3",
"category_id": "12",
"item_name": "Waffles",
"item_image": "item_081220170335.jpg",
"is_variant": "0",
"item_price": "7",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "item",
}
];
itemsArr[1].extras = [extraObj];
// result
[
{
"item_id": "3",
"category_id": "12",
"item_name": "Waffles",
"item_image": "item_081220170335.jpg",
"is_variant": "0",
"item_price": "7",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "item",
"extras": [
{
"item_id": "4",
"item_name": "Extra Patty",
"item_image": "placeholder_img.jpg",
"item_price": "3.00",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "extra"
}
]
},
{
"item_id": "3",
"category_id": "12",
"item_name": "Waffles",
"item_image": "item_081220170335.jpg",
"is_variant": "0",
"item_price": "7",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "item",
"extras": [
{
"item_id": "4",
"item_name": "Extra Patty",
"item_image": "placeholder_img.jpg",
"item_price": "3.00",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "extra"
}
]
}
]
case SET_FOOD_EXTRAS:
const { itemId, extra, extraIndex, itemIndex } = action.payload;
const cloneItems = cloneDeep([...state.items]);
// cloneItems.splice(itemIndex, 0, { extras: [extra] });
cloneItems[itemIndex].extras = [extra];
return {
...state,
items: cloneItems,
summary: setSummary(state, cloneItems)
};

It depends on how you populate your itemsArr.
If you do something like:
const ob1 = {
"item_id": "3",
"category_id": "12",
"item_name": "Waffles",
"item_image": "item_081220170335.jpg",
"is_variant": "0",
"item_price": "7",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "item"
}
itemsArr.push(ob1);
itemsArr.push(ob1);
Then, both items in the array point to the same object so any modifications to one will be reflected on the other.
One solution is to make copies of the object:
itemsArr.push({...ob1});
itemsArr.push({..ob1});

Related

How can we easily remove an element from an multi dimensional array object in react js

I am working in react Js. There is a trouble for me to remove an item corresponding to "product_option_value_id" .I need to remove item from product_option_value ( child array object) if my given itemId==product_option_value_id, and return whole array object after removing the specified item. I think the idea is clear . I tried a method , but I got undefined.
"default": 0,
"master_option": 0,
" master_option_value": 0,
"maximum": 0,
"minimum": 0,
"name": "Choose Size",
"option_id": "4",
"product_option_id": "111",
"product_option_value": [{
"ec_product_id": "",
"exclude_others": "0",
"image": "",
"master_option_value": "0",
"name": "25ml",
"option_value_id": "8",
"points": "0",
"product_option_value_id": "267"
},
{
" ec_product_id": "22w",
"exclude_others": "0",
"image": "",
"master_option_value": "0",
"name": "25ml",
"option_value_id": "8",
"points": "0",
"product_option_value_id": "266"
}
]
},
{
"default": 0,
"master_option": 0,
" master_option_value": 0,
"maximum": 0,
"minimum": 0,
"name": "Water",
"option_id": "4",
"product_option_id": "111",
"product_option_value": [{
"ec_product_id": "",
"exclude_others": "0",
"image": "",
"master_option_value": "0",
"name": "25ml",
"option_value_id": "8",
"points": "0",
"product_option_value_id": "700"
},
{
" ec_product_id": "22w",
"exclude_others": "0",
"image": "",
"master_option_value": "0",
"name": "50ml",
"option_value_id": "8",
"points": "0",
"product_option_value_id": "701"
},
{
" ec_product_id": "22w",
"exclude_others": "0",
"image": "",
"master_option_value": "0",
"name": "500ml",
"option_value_id": "8",
"points": "0",
"product_option_value_id": "702"
}, {
" ec_product_id": "22w",
"exclude_others": "0",
"image": "",
"master_option_value": "0",
"name": "500ml",
"option_value_id": "8",
"points": "0",
"product_option_value_id": "703"
}
]
}
]
The method I tried
const removeOption=(itemId:any)=>{
const filteredItems = productOptions.forEach(function(o:any) {
o.product_option_value = o.product_option_value.filter((s:any) => s.product_option_value_id != itemId);
});
}
Well, the forEach method does not return the array, that is why you are getting undefined as result. This method just perform a function for each element:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
So you need to use the .map() method instead:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
so basically:
const removeOption = (itemId: any) => {
return productOptions.map((o: any) => {
return { ...o, product_option_value: o.product_option_value.filter((s: any) => s.product_option_value_id !== itemId)};
});
}

Grouping objects using two arrays into new array

I have to group products from the products array based on the season which is given in the orders array. The orders array has the season key-value pair (eg. "season": "2015" ). The products can be mapped to the individual order object with the "id" of the order array and the "orderlineId" of the products array.
When I have the products grouped by season, they also need to be grouped based on "uniqueId" and "colorCode" which is inside product.uniqueId and product.colorCode.
Orders array
{
"id": 99945333,
"key": "1",
"orderNumber": "01",
"season": "2007"
},
{
"id": 99945335,
"key": "1",
"orderNumber": "02",
"season": "2016"
},
{
"id": 99945333,
"key": "2",
"orderNumber": "03",
"season": "2019"
},
{
"id": 99945333,
"key": "3",
"orderNumber": "04",
"season": "2017"
}
]
products array
"orderlineId": 99945333,
"product": {
"season": null,
"size": "XXL",
"category: "pants"
"sizeSortCode": "60",
"subSize": null,
"subSizeSortCode": "0",
"uniqueId": "80457",
"year": null
},
"quantity": 1,
"quantityDelivered": 0,
"remark": null
},
{
"orderlineId": 99945333,
"product": {
"season": null,
"size": "XXL",
"category: "pants"
"sizeSortCode": "60",
"subSize": null,
"subSizeSortCode": "0",
"uniqueId": "80457",
"year": null
},
"quantity": 1,
"quantityDelivered": 0,
"remark": null
},
{
"orderlineId": 99945335,
"product": {
"season": null,
"size": "XXL",
"category: "shirt"
"sizeSortCode": "60",
"subSize": null,
"subSizeSortCode": "0",
"uniqueId": "80457",
"year": null
},
"quantity": 1,
"quantityDelivered": 0,
"remark": null
},
{
"orderlineId": 99945335,
"product": {
"season": null,
"size": "XXL",
"category: "trouser"
"sizeSortCode": "60",
"subSize": null,
"subSizeSortCode": "0",
"uniqueId": "80453",
"year": null
},
"quantity": 1,
"quantityDelivered": 0,
"remark": null
},
{
"orderlineId": 99945473,
"product": {
"season": null,
"category: "blouse"
"size": "XXL",
"sizeSortCode": "60",
"subSize": null,
"subSizeSortCode": "0",
"uniqueId": "80453",
"year": null
},
"quantity": 1,
"quantityDelivered": 0,
"remark": null
},
I think a new array would be best here so I iterate over them more easily.
desired outcome: new array
{
"season": 2007,
"products": [
{
"season": null,
"size": "XXL",
"category: "pants"
"sizeSortCode": "60",
"subSize": null,
"subSizeSortCode": "0",
"uniqueId": "80453",
"year": null
}
{
"season": null,
"size": "XXL",
"sizeSortCode": "60",
"subSize": null,
"subSizeSortCode": "0",
"uniqueId": "80453",
"year": null
}
},
{
"season": 2016,
"products": [
{
"season": null,
"size": "XXL",
"sizeSortCode": "60",
"subSize": null,
"subSizeSortCode": "0",
"uniqueId": "80457",
"year": null
},
},
{
"season": null,
"size": "XXL",
"sizeSortCode": "60",
"subSize": null,
"subSizeSortCode": "0",
"uniqueId": "80453",
"year": null
}
}
]
I found it quite tricky to do. I assume I should map over the seasons first, but not sure how to group the products and build a new array. Help is much appreciated!
Ah,
I think I found a sufficient answer to my own question. It's not exactly like the desired output, but I can work with it!. I used:
const sortedSeasons = orders.concat(products).reduce((acc, currentVal) => {
acc[currentVal.season] = Object.assign(acc[currentVal.id] || {}, currentVal);
return acc;
}, {});
Object.keys(sortedSeasons).map(i => sortedSeasons[i]);

Get count of arrays returned in $.each

Seems like a simple question but can't find a result anywhere in JQuery help or on SO. How do I get the count of the number of arrays returned from JSON array. cust_id may return 2 arrays or as many as 10.
$.each(data, function() {
if (this.cust_id == selectedProductAutonum) {
invoices = this;
return true;
alert(this.length);
}
});
example JSON:
var myjson = [{
"autonum": "20",
"date": "2017-03-22",
"customer": "Jeffs Music\r\n",
"address": "Montgomery Station",
"invoice": "20160929",
"sales": "2416.00",
"paid": "1000.00",
"owed": "1416.00",
"tax": "0.00",
"misc": "2017-03-22 19:51:00",
"cust_id": "15",
"product": "Labor",
"description": "Complete Install Labor only (DVR configuration, Install, Pow",
"cost": "2150.00",
"quantity": "1",
"price": "2150.00",
"timestamp": "2017-03-22 19:51:00"
}, {
"autonum": "21",
"date": "2017-03-22",
"customer": "Jeffs Music\r\n",
"address": "Montgomery Station",
"invoice": "20160929",
"sales": "2416.00",
"paid": "1000.00",
"owed": "1416.00",
"tax": "0.00",
"misc": "2017-03-22 19:51:00",
"cust_id": "15",
"product": "Home Depot",
"description": "Home Depot Supplies for Shelf/mounts/braces/paint.",
"cost": "128.50",
"quantity": "1",
"price": "128.50",
"timestamp": "2017-03-22 19:51:00"
}, {
"autonum": "22",
"date": "2017-03-22",
"customer": "Mikes Music\r\n",
"address": "Montgomery Station",
"invoice": "20160929",
"sales": "2416.00",
"paid": "1000.00",
"owed": "1416.00",
"tax": "0.00",
"misc": "2017-03-22 19:51:00",
"cust_id": "15",
"product": "Cables",
"description": "Cables and Connectors / power pigtails",
"cost": "43.85",
"quantity": "1",
"price": "43.85",
"timestamp": "2017-03-22 19:51:00"
}, {
"autonum": "23",
"date": "2017-03-22",
"customer": "Jeffs Music\r\n",
"address": "Montgomery Station",
"invoice": "20160929",
"sales": "2416.00",
"paid": "1000.00",
"owed": "1416.00",
"tax": "0.00",
"misc": "2017-03-22 19:51:00",
"cust_id": "10",
"product": "Cables",
"description": "Cables and connectors / hardware used in November 2016",
"cost": "45.55",
"quantity": "1",
"price": "45.55",
"timestamp": "2017-03-22 19:51:00"
}, {
"autonum": "24",
"date": "2017-03-22",
"customer": "Jeffs Music\r\n",
"address": "Montgomery Station",
"invoice": "20160929",
"sales": "2416.00",
"paid": "1000.00",
"owed": "1416.00",
"tax": "0.00",
"misc": "2017-03-22 19:51:00",
"cust_id": "10",
"product": "Cables",
"description": "Extension power supply cables",
"cost": "43.12",
"quantity": "1",
"price": "43.12",
"timestamp": "2017-03-22 19:51:00"
}]
You can use the function filter to get a array of objects which have cust_id === "10".
var myjson = [{ "autonum": "20", "date": "2017-03-22", "customer": "Jeffs Music\r\n", "address": "Montgomery Station", "invoice": "20160929", "sales": "2416.00", "paid": "1000.00", "owed": "1416.00", "tax": "0.00", "misc": "2017-03-22 19:51:00", "cust_id": "15", "product": "Labor", "description": "Complete Install Labor only (DVR configuration, Install, Pow", "cost": "2150.00", "quantity": "1", "price": "2150.00", "timestamp": "2017-03-22 19:51:00"}, { "autonum": "21", "date": "2017-03-22", "customer": "Jeffs Music\r\n", "address": "Montgomery Station", "invoice": "20160929", "sales": "2416.00", "paid": "1000.00", "owed": "1416.00", "tax": "0.00", "misc": "2017-03-22 19:51:00", "cust_id": "15", "product": "Home Depot", "description": "Home Depot Supplies for Shelf/mounts/braces/paint.", "cost": "128.50", "quantity": "1", "price": "128.50", "timestamp": "2017-03-22 19:51:00"}, { "autonum": "22", "date": "2017-03-22", "customer": "Mikes Music\r\n", "address": "Montgomery Station", "invoice": "20160929", "sales": "2416.00", "paid": "1000.00", "owed": "1416.00", "tax": "0.00", "misc": "2017-03-22 19:51:00", "cust_id": "15", "product": "Cables", "description": "Cables and Connectors / power pigtails", "cost": "43.85", "quantity": "1", "price": "43.85", "timestamp": "2017-03-22 19:51:00"}, { "autonum": "23", "date": "2017-03-22", "customer": "Jeffs Music\r\n", "address": "Montgomery Station", "invoice": "20160929", "sales": "2416.00", "paid": "1000.00", "owed": "1416.00", "tax": "0.00", "misc": "2017-03-22 19:51:00", "cust_id": "10", "product": "Cables", "description": "Cables and connectors / hardware used in November 2016", "cost": "45.55", "quantity": "1", "price": "45.55", "timestamp": "2017-03-22 19:51:00"}, { "autonum": "24", "date": "2017-03-22", "customer": "Jeffs Music\r\n", "address": "Montgomery Station", "invoice": "20160929", "sales": "2416.00", "paid": "1000.00", "owed": "1416.00", "tax": "0.00", "misc": "2017-03-22 19:51:00", "cust_id": "10", "product": "Cables", "description": "Extension power supply cables", "cost": "43.12", "quantity": "1", "price": "43.12", "timestamp": "2017-03-22 19:51:00"}],
selectedProductAutonum = "10",
result = myjson.filter(({cust_id}) => cust_id === selectedProductAutonum);
console.log("Length:", result.length);
selectedProductAutonum = "15";
result = myjson.filter(({cust_id}) => cust_id === selectedProductAutonum);
console.log("Length:", result.length);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use Array.prototype.filter()
const filterProp = (data, prop, match) => data.filter(({[prop]:p}) => p == match)
let selectedProductAutonum = "15"
let {length: len} = filterProp(myjson, "cust_id", selectedProductAutonum)
console.log(len)

How to find out similar objects in array - react js

I have seen similar questions about duplicate objects.
my json output:
{ "coupons": [
{
"id": "376363",
"price": "14400",
"date": "2018-04-08 10:40:17",
"user_id": "16433",
"ip": "46.225.123.235",
"code": "5ac9b249a0cc5",
"succ": "1",
"admin_seen": "1",
"user_seen": "0",
"coupon_id": "20821",
"coupon_parent": "20821",
"coupon_code": "195_2484C1_9873(7531)",
"coupon_code_user": "7531",
"coupon_code_partner": "195_2484C1_9873",
"shop_id": "2484",
"payment_type": "7",
"merchent_type": "3",
"merchent_id": "0",
"cradit_start_date": "2018-03-24 05:05:05",
"cradit_end_date": "2018-04-22 05:05:05",
"expired": "0",
"pay_data": null,
"seri": "C",
"to_friend": "0",
"finance_id": "0",
"app": "web",
"expire_date": "0000-00-00 00:00:00",
"expire_app": "",
"buy_id": "5ac9b249970c2",
"coupon_property_id": "0",
"title": "title1",
"coupon_property_title": "",
"parent_title": ""
},
{
"id": "376362",
"price": "14400",
"date": "2018-04-08 10:40:17",
"user_id": "16433",
"ip": "46.225.123.235",
"code": "5ac9b24997103",
"succ": "1",
"admin_seen": "1",
"user_seen": "0",
"coupon_id": "20821",
"coupon_parent": "20821",
"coupon_code": "194_2484C1_9779(4478)",
"coupon_code_user": "4478",
"coupon_code_partner": "194_2484C1_9779",
"shop_id": "2484",
"payment_type": "7",
"merchent_type": "3",
"merchent_id": "0",
"cradit_start_date": "2018-03-24 05:05:05",
"cradit_end_date": "2018-04-22 05:05:05",
"expired": "0",
"pay_data": null,
"seri": "C",
"to_friend": "0",
"finance_id": "0",
"app": "web",
"expire_date": "0000-00-00 00:00:00",
"expire_app": "",
"buy_id": "5ac9b249970c2",
"coupon_property_id": "0",
"title": "title2",
"coupon_property_title": "",
"parent_title": ""
},
{
"id": "341459",
"price": "27000",
"date": "2017-03-07 10:42:47",
"user_id": "16433",
"ip": "46.225.76.21",
"code": "58be5d6fd7214",
"succ": "1",
"admin_seen": "1",
"user_seen": "0",
"coupon_id": "19457",
"coupon_parent": "19457",
"coupon_code": "7_1310B1_2389(3386)",
"coupon_code_user": "3386",
"coupon_code_partner": "7_1310B1_2389",
"shop_id": "1310",
"payment_type": "7",
"merchent_type": "3",
"merchent_id": "0",
"cradit_start_date": "2017-01-16 05:05:05",
"cradit_end_date": "2017-03-19 05:05:05",
"expired": "11",
"pay_data": null,
"seri": "B",
"to_friend": "0",
"finance_id": "0",
"app": "web",
"expire_date": "0000-00-00 00:00:00",
"expire_app": "",
"buy_id": "58be5d6fd71c6",
"coupon_property_id": "0",
"title": "title3",
"coupon_property_title": "",
"parent_title": ""
},
{
"id": "341456",
"price": "11250",
"date": "2017-03-07 10:34:54",
"user_id": "16433",
"ip": "46.225.76.21",
"code": "58be5b964bf1d",
"succ": "1",
"admin_seen": "1",
"user_seen": "0",
"coupon_id": "19724",
"coupon_parent": "19724",
"coupon_code": "16_2129A1_2178(4663)",
"coupon_code_user": "4663",
"coupon_code_partner": "16_2129A1_2178",
"shop_id": "2129",
"payment_type": "7",
"merchent_type": "3",
"merchent_id": "0",
"cradit_start_date": "2017-03-05 05:05:05",
"cradit_end_date": "2017-05-05 05:05:05",
"expired": "11",
"pay_data": null,
"seri": "A",
"to_friend": "0",
"finance_id": "0",
"app": "web",
"expire_date": "0000-00-00 00:00:00",
"expire_app": "",
"buy_id": "58be5b964b1a1",
"coupon_property_id": "0",
"title": "title4",
"coupon_property_title": "",
"parent_title": ""
}
]
}
each object has a buy_id field. buy_id shows that the objects are the same and I should print them inside one row of html table.
for example the first object and the second object are the same depending on buy_id I print them inside row. output:
---------
title1 - title2 //because the first object and second object have same `buy_id`
---------
title3
---------
title4
should I use two maps?
I should use this scenario inside return of render function.
I put a bet on reduce for that.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
the following snippets will group your objects by buy_id, then you can render them easily
const data = { "coupons": [
{
"id": "376363",
"price": "14400",
"date": "2018-04-08 10:40:17",
"user_id": "16433",
"ip": "46.225.123.235",
"code": "5ac9b249a0cc5",
"succ": "1",
"admin_seen": "1",
"user_seen": "0",
"coupon_id": "20821",
"coupon_parent": "20821",
"coupon_code": "195_2484C1_9873(7531)",
"coupon_code_user": "7531",
"coupon_code_partner": "195_2484C1_9873",
"shop_id": "2484",
"payment_type": "7",
"merchent_type": "3",
"merchent_id": "0",
"cradit_start_date": "2018-03-24 05:05:05",
"cradit_end_date": "2018-04-22 05:05:05",
"expired": "0",
"pay_data": null,
"seri": "C",
"to_friend": "0",
"finance_id": "0",
"app": "web",
"expire_date": "0000-00-00 00:00:00",
"expire_app": "",
"buy_id": "5ac9b249970c2",
"coupon_property_id": "0",
"title": "title1",
"coupon_property_title": "",
"parent_title": ""
},
{
"id": "376362",
"price": "14400",
"date": "2018-04-08 10:40:17",
"user_id": "16433",
"ip": "46.225.123.235",
"code": "5ac9b24997103",
"succ": "1",
"admin_seen": "1",
"user_seen": "0",
"coupon_id": "20821",
"coupon_parent": "20821",
"coupon_code": "194_2484C1_9779(4478)",
"coupon_code_user": "4478",
"coupon_code_partner": "194_2484C1_9779",
"shop_id": "2484",
"payment_type": "7",
"merchent_type": "3",
"merchent_id": "0",
"cradit_start_date": "2018-03-24 05:05:05",
"cradit_end_date": "2018-04-22 05:05:05",
"expired": "0",
"pay_data": null,
"seri": "C",
"to_friend": "0",
"finance_id": "0",
"app": "web",
"expire_date": "0000-00-00 00:00:00",
"expire_app": "",
"buy_id": "5ac9b249970c2",
"coupon_property_id": "0",
"title": "title2",
"coupon_property_title": "",
"parent_title": ""
},
{
"id": "341459",
"price": "27000",
"date": "2017-03-07 10:42:47",
"user_id": "16433",
"ip": "46.225.76.21",
"code": "58be5d6fd7214",
"succ": "1",
"admin_seen": "1",
"user_seen": "0",
"coupon_id": "19457",
"coupon_parent": "19457",
"coupon_code": "7_1310B1_2389(3386)",
"coupon_code_user": "3386",
"coupon_code_partner": "7_1310B1_2389",
"shop_id": "1310",
"payment_type": "7",
"merchent_type": "3",
"merchent_id": "0",
"cradit_start_date": "2017-01-16 05:05:05",
"cradit_end_date": "2017-03-19 05:05:05",
"expired": "11",
"pay_data": null,
"seri": "B",
"to_friend": "0",
"finance_id": "0",
"app": "web",
"expire_date": "0000-00-00 00:00:00",
"expire_app": "",
"buy_id": "58be5d6fd71c6",
"coupon_property_id": "0",
"title": "title3",
"coupon_property_title": "",
"parent_title": ""
},
{
"id": "341456",
"price": "11250",
"date": "2017-03-07 10:34:54",
"user_id": "16433",
"ip": "46.225.76.21",
"code": "58be5b964bf1d",
"succ": "1",
"admin_seen": "1",
"user_seen": "0",
"coupon_id": "19724",
"coupon_parent": "19724",
"coupon_code": "16_2129A1_2178(4663)",
"coupon_code_user": "4663",
"coupon_code_partner": "16_2129A1_2178",
"shop_id": "2129",
"payment_type": "7",
"merchent_type": "3",
"merchent_id": "0",
"cradit_start_date": "2017-03-05 05:05:05",
"cradit_end_date": "2017-05-05 05:05:05",
"expired": "11",
"pay_data": null,
"seri": "A",
"to_friend": "0",
"finance_id": "0",
"app": "web",
"expire_date": "0000-00-00 00:00:00",
"expire_app": "",
"buy_id": "58be5b964b1a1",
"coupon_property_id": "0",
"title": "title4",
"coupon_property_title": "",
"parent_title": ""
}
]
};
const reducedData = data.coupons.reduce((accumulator, value) => {
accumulator[value.buy_id] = accumulator[value.buy_id] || [];
accumulator[value.buy_id].push(value);
return accumulator;
}, {});
console.log(reducedData);
You have to use reduce :
data.coupons.reduce((acc,value)=>{
return acc[value.buy_id] === undefined
? {...acc,[value.buy_id]:value.title}
: {...acc,[value.buy_id]:`${acc[value.buy_id]} - ${value.title}`}
},{})
The result is :
{
"5ac9b249970c2": "title1 - title2",
"58be5d6fd71c6": "title3",
"58be5b964b1a1": "title4"
}

Explore recursively an Object with Underscore and convert field type

I'm working with some custom jSON objects.
I'm trying to explore this whole object, and to change field type.
For exemple, real_id or clean_id and even temperature need to be converted as Integer.
To deal with that, I started to make a function which is very simple :
var reg = /^\d+$/;
_.each(myObject, function(val, key) {
myObject[key] = reg.test(val) ? parseInt(val) :val;
});
I got several needs :
it will check every field one by one on the first level, but if myObject has elements which themselves include object or array of object, my _.each won't explore them.
For now it can detect integer thanks to the regex, and convert them to Integer but what if I need to convert a float?
If I find null I need to set it to 0 instead
On my exemple below,
Exemple of Sample of jSON object :
myObject = {
"real_name": "Test",
"maker": "Jean-Paul",
"company": "",
"real_id": "646402",
"clean_id": "152691",
"year": 2013,
"type": "Red real",
"available_for_order": 0,
"level": null,
"bio": null,
"temperature": "15",
"potential": "3",
"country_code": "USA",
"coord_lng": "2.7014349999999",
"coord_lat": "42.717317",
"real_description": [
{
"comment": "Real good stuff",
"lang": "it",
"video_end": null,
"video_id": null,
"video_start": null,
"video_url": null
},
{
"comment": "Awesome and cheap stuff",
"lang": "en",
"video_end": null,
"video_id": null,
"video_start": null,
"video_url": null
}
],
"full_description": [
{
"description": "Long description",
"lang": "fr"
},
{
"description": "",
"lang": "en"
}
],
"list": [
{
"available_for_order": "0",
"capacity": "4500",
"conciergerie": "0",
"currency_code": "EUR",
"price": 0,
"quantity": 0,
"retail_price": 0,
"real_id": "656732",
"year": "1"
},
{
"available_for_order": "0",
"capacity": "4500",
"conciergerie": "0",
"currency_code": "EUR",
"price": 0,
"quantity": 0,
"retail_price": 0,
"real_id": "330381",
"year": "2008"
},
{
"available_for_order": "0",
"capacity": "4500",
"conciergerie": "0",
"currency_code": "EUR",
"price": 20,
"quantity": 0,
"retail_price": 0,
"real_id": "11453216",
"year": "2010"
},
{
"available_for_order": "0",
"capacity": "4500",
"conciergerie": "0",
"currency_code": "EUR",
"price": 0,
"quantity": 0,
"retail_price": 0,
"real_id": "11497420",
"year": "2011"
},
{
"available_for_order": "0",
"capacity": "4500",
"conciergerie": "1",
"currency_code": "EUR",
"price": 10,
"quantity": 0,
"retail_price": 0,
"real_id": "11506715",
"year": "2012"
},
{
"available_for_order": "1",
"capacity": "4500",
"conciergerie": "0",
"currency_code": "EUR",
"price": 10,
"quantity": 0,
"retail_price": 0,
"real_id": "11458207",
"year": "2013"
}
],
"check_list": [
"3",
"8",
"9",
"10",
"14"
],
"image_src": "791330_31odFZZoM2_JqkCPJGHXa_4500x1000.jpeg"
}
Thanks a lot for your help
What you need, in my opinion, is a simple example of recursion, Lodash isn't required...
NOTE: You're using a regex that matches only string that starts and ends with a one or more occurrence of digit...
So, instead of using parseInt or parseFloat, you should use Number to cast values!
In Javascript Number is the constructor of the type Number, but, if called without the new operator, performs a basic Casting.
It returns NaN when the casting is unsatisfable, so, using the or operator we can keep the original value!
Hope Helps...
var myObject = {
"real_name": "Test",
"maker": "Jean-Paul",
"company": "",
"real_id": "646402",
"clean_id": "152691",
"year": 2013,
"type": "Red real",
"available_for_order": 0,
"level": null,
"bio": null,
"temperature": "15",
"potential": "3",
"country_code": "USA",
"coord_lng": "2.7014349999999",
"coord_lat": "42.717317",
"real_description": [
{
"comment": "Real good stuff",
"lang": "it",
"video_end": null,
"video_id": null,
"video_start": null,
"video_url": null
},
{
"comment": "Awesome and cheap stuff",
"lang": "en",
"video_end": null,
"video_id": null,
"video_start": null,
"video_url": null
}
],
"full_description": [
{
"description": "Long description",
"lang": "fr"
},
{
"description": "",
"lang": "en"
}
],
"list": [
{
"available_for_order": "0",
"capacity": "4500",
"conciergerie": "0",
"currency_code": "EUR",
"price": 0,
"quantity": 0,
"retail_price": 0,
"real_id": "656732",
"year": "1"
},
{
"available_for_order": "0",
"capacity": "4500",
"conciergerie": "0",
"currency_code": "EUR",
"price": 0,
"quantity": 0,
"retail_price": 0,
"real_id": "330381",
"year": "2008"
},
{
"available_for_order": "0",
"capacity": "4500",
"conciergerie": "0",
"currency_code": "EUR",
"price": 20,
"quantity": 0,
"retail_price": 0,
"real_id": "11453216",
"year": "2010"
},
{
"available_for_order": "0",
"capacity": "4500",
"conciergerie": "0",
"currency_code": "EUR",
"price": 0,
"quantity": 0,
"retail_price": 0,
"real_id": "11497420",
"year": "2011"
},
{
"available_for_order": "0",
"capacity": "4500",
"conciergerie": "1",
"currency_code": "EUR",
"price": 10,
"quantity": 0,
"retail_price": 0,
"real_id": "11506715",
"year": "2012"
},
{
"available_for_order": "1",
"capacity": "4500",
"conciergerie": "0",
"currency_code": "EUR",
"price": 10,
"quantity": 0,
"retail_price": 0,
"real_id": "11458207",
"year": "2013"
}
],
"check_list": [
"3",
"8",
"9",
"10",
"14"
],
"image_src": "791330_31odFZZoM2_JqkCPJGHXa_4500x1000.jpeg"
};
function recurse(obj) {
for(var key in obj) {
if(!obj.hasOwnProperty(key)) { continue; }
if('object' === typeof obj[key]) {
recurse(obj[key]);
} else {
console.log(key, obj[key], typeof obj[key], ' ==> ', typeof (Number(obj[key]) || obj[key]));
obj[key] = Number(obj[key]) || obj[key];
}
}
}
recurse(myObject);
var parseObjectProperties = function (obj) {
_.each(obj, function(val, key) {
if (typeof(key) === 'object') {
parseObjectProperties(key);
} else {
if (getType(val) === 'float') {
myObject[key] = parseFloat(val);
} else if (getType(val) === 'int') {
myObject[key] = parseInt(val);
} else if (val === null) {
myObject[key] = 0;
}
}
});
};
var getType = function(input) {
var match = (/[\d]+(\.[\d]+)?/).exec(input);
if (match ) {
if (match [1]) {
return 'float';
} else {
return 'int';
}
}
return 'string';
}
exploreObject(myObject);

Categories

Resources