Reformat Array of objects using array.map - javascript

I receive the result of an API call with the following array, I am trying to reformat this Array from:
const items = [
{
id: 1,
name: "Item 1",
section: { name: "Section A" }
},
{
id: 2,
name: "Item 2",
section: { name: "Section A" }
},
{
id: 3,
name: "Item 3",
section: { name: "Section A" }
},
{
id: 4,
name: "Item 4",
section: { name: "Section B" }
},
{
id: 5,
name: "Item 5",
section: { name: "Section B" }
},
{
id: 6,
name: "Item 6",
section: { name: "Section C" }
},
{
id: 7,
name: "Item 7",
section: { name: "Section C" }
}
];
To Array this:
const items = [
{
section: "Section A",
items: [
{
id: 1,
item: "Item 1"
},
{
id: 2,
item: "Item 2"
},
{
id: 3,
item: "Item 3"
}]
},
{
section: "Section B",
items: [
{
id: 4,
item: "Item 4"
},
{
id: 5,
item: "Item 5"
}]
},
{
section: "Section C",
items: [
{
id: 6,
item: "Item 6"
},
{
id: 7,
item: "Item 7"
}]
},
]
I have tried the following function:
const result = Array.from(new Set(items.map(s => s.section.name)))
.map(section => {
return {
section: section,
items: Array.from(new Set(items.map(function (item) {
if (item.section.name === section) {
return item.name
}
}
)))
}
})
This gives me the following result, which is close but I am not sure why I am getting the undefined values?
//[{section: "Section A", items: ["Item 1", "Item 2", "Item 3", undefined]},{section: "Section B", items:[undefined, "Item 4", "Item 5"]},{section: "Section C", items: [undefined, "Item 6", "Item 7"]}]
Can anyone assist me to correct this function or suggest a better approach?

You could take an object for grouping and get the values as result.
const
items = [{ id: 1, name: "Item 1", section: { name: "Section A" } }, { id: 2, name: "Item 2", section: { name: "Section A" } }, { id: 3, name: "Item 3", section: { name: "Section A" } }, { id: 4, name: "Item 4", section: { name: "Section B" } }, { id: 5, name: "Item 5", section: { name: "Section B" } }, { id: 6, name: "Item 6", section: { name: "Section C" } }, { id: 7, name: "Item 7", section: { name: "Section C" } }],
result = Object.values(items.reduce((r, { section: { name: section }, ...item }) => {
if (!r[section]) r[section] = { section, items: [] };
r[section].items.push(item);
return r;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can use Array prototype methods reduce() and findIndex()
like this:
const items = [
{
id: 1,
name: "Item 1",
section: { name: "Section A" }
},
{
id: 2,
name: "Item 2",
section: { name: "Section A" }
},
{
id: 3,
name: "Item 3",
section: { name: "Section A" }
},
{
id: 4,
name: "Item 4",
section: { name: "Section B" }
},
{
id: 5,
name: "Item 5",
section: { name: "Section B" }
},
{
id: 6,
name: "Item 6",
section: { name: "Section C" }
},
{
id: 7,
name: "Item 7",
section: { name: "Section C" }
}
];
const res = items.reduce((acc, curr) => {
const index = acc && acc.findIndex(({ section }) => section === curr.section.name)
if(index !== -1) {
acc[index].items.push({ id: curr.id, item: curr.name });
}
else {
acc.push({section: curr.section.name, items: [{ id: curr.id, item: curr.name }]});
}
return acc;
}, []);
console.log(res);

Related

Only show list of items that match all values in different array

I currently have an array of selectedCategories and list of products that looks like this:
let selectedCategories = []
let productList = []
and a JSON list of products which looks like this:
let products = [
{
"id": 1,
...
"categories": [
{ "name": "Category 1", "count": 1 },
{ "name": "Category 2", "count": 1 },
{ "name": "Category 3", "count": 1 }
],
...
},
{
"id": 2,
...
"categories": [
{ "name": "Category 4", "count": 1 },
{ "name": "Category 5", "count": 2 },
{ "name": "Category 6", "count": 1 }
],
...
},
{
"id": 3,
...
"categories": [
{ "name": "Category 5", "count": 1 }
],
...
}
]
I only want to show the products that match the values in the selectedCategories array. I've tried both every and includes, but cannot seem to get the desired result:
this.products.filter(product => {
product.categories.filter(category => {
if (this.selectedCategories.includes(category.name)) {
productList.push(product)
}
})
})
and
this.products.filter(product => {
product.categories.filter(category => {
this.selectedCategories.every(value => {
if (value === category.name) {
productList.push(product)
}
})
})
})
The problem is that in the code above, it doesnt check if all values in the array match, but only if it occurs.
Wished output is something like:
selectedCategories = [ "Category 5" ]
>>> productList = [{id: 2}, {id: 3}]
selectedCategories = [ "Category 5", "Category 4" ]
>>> productList = [{id: 2}]
How can i achieve this?
Edit:
How can i filter on multiple arrays in the product object?
Product structure:
[
{
"id": 1,
...
"categories": [
{ "name": "Category 1", "count": 1 },
{ "name": "Category 2", "count": 1 },
{ "name": "Category 3", "count": 1 }
],
"styles": [
{ name: "Style 1", count: 1 },
{ name: "Style 2", count: 1 },
]
...
},
{
"id": 2,
...
"categories": [
{ "name": "Category 4", "count": 1 },
{ "name": "Category 5", "count": 2 },
{ "name": "Category 6", "count": 1 }
],
"styles": [
{ name: "Style 3", count: 1 },
{ name: "Style 4", count: 1 },
]
...
},
{
"id": 3,
...
"categories": [
{ "name": "Category 5", "count": 1 }
],
"styles": [
{ name: "Style 3", count: 1 },
]
...
}
]
Expected output:
selectedCategories = [ "Category 5" ]
>>> productList = [{id: 2}, {id: 3}]
selectedCategories = [ "Category 5", "Style 3" ]
>>> productList = [{id: 2}, {id: 3}]
selectedCategories = [ "Category 5", "Style 3", "Style 4" ]
>>> productList = [{id: 2}]
You need filter+every+some+map to get your desired output:
const products = [ { "id": 1, "categories": [ { "name": "Category 1", "count": 1 }, { "name": "Category 2", "count": 1 }, { "name": "Category 3", "count": 1 } ], "styles": [ { name: "Style 1", count: 1 }, { name: "Style 2", count: 1 }, ] }, { "id": 2, "categories": [ { "name": "Category 4", "count": 1 }, { "name": "Category 5", "count": 2 }, { "name": "Category 6", "count": 1 } ], "styles": [ { name: "Style 3", count: 1 }, { name: "Style 4", count: 1 }, ] }, { "id": 3, "categories": [ { "name": "Category 5", "count": 1 } ], "styles": [ { name: "Style 3", count: 1 }, ] } ];
const selectedCategories = [ "Category 5", "Style 3", "Style 4" ]
const result = products.filter(p=>selectedCategories.every(k=>p.categories.some(t=>t.name==k) || p.styles.some(s=>s.name==k))).map(({id})=>({id}));
console.log(result);
You could combine the use of filter and every
const getProductList = (products, selectedCategories) => {
return products
.filter((product) => {
const productCategories = product.categories.map(
(category) => category.name
)
return selectedCategories.every((selectedCategory) =>
productCategories.includes(selectedCategory)
)
})
.map((product) => ({ id: product.id }))
}
Full demo
const products = [
{
id: 1,
categories: [
{ name: "Category 1", count: 1 },
{ name: "Category 2", count: 1 },
{ name: "Category 3", count: 1 },
],
},
{
id: 2,
categories: [
{ name: "Category 4", count: 1 },
{ name: "Category 5", count: 2 },
{ name: "Category 6", count: 1 },
],
},
{
id: 3,
categories: [{ name: "Category 5", count: 1 }],
},
]
const getProductList = (products, selectedCategories) => {
return products
.filter((product) => {
const productCategories = product.categories.map(
(category) => category.name
)
return selectedCategories.every((selectedCategory) =>
productCategories.includes(selectedCategory)
)
})
.map((product) => ({ id: product.id }))
}
console.log(getProductList(products, ["Category 5"]))
console.log(getProductList(products, ["Category 5", "Category 4"]))
.as-console-wrapper { max-height: 100% !important; }
You should return (either with the return keyword or with the implicit return of arrow functions) inside the array methods for them to be useful. After filtering, .map each to an object containing only the ID:
const getFiltered = (selectedCategories) => {
const productList = products
.filter(({ categories }) => selectedCategories.every(
requiredCat => categories.some(
prodCat => prodCat.name === requiredCat
)
))
.map(({ id }) => ({ id }));
console.log(productList);
};
const products = [
{
"id": 1,
"categories": [
{ "name": "Category 1", "count": 1 },
{ "name": "Category 2", "count": 1 },
{ "name": "Category 3", "count": 1 }
],
},
{
"id": 2,
"categories": [
{ "name": "Category 4", "count": 1 },
{ "name": "Category 5", "count": 2 },
{ "name": "Category 6", "count": 1 }
],
},
{
"id": 3,
"categories": [
{ "name": "Category 5", "count": 1 }
],
}
];
getFiltered(['Category 5', 'Category 4']);
getFiltered(['Category 5']);
You need to iterate the cateories as well.
const
filterByCategories = (products, categories) =>
products.filter(product =>
categories.every(category =>
product.categories.some(c => category === c.name)
)
),
products = [{ id: 1, categories: [{ name: "Category 1", count: 1 }, { name: "Category 2", count: 1 }, { name: "Category 3", count: 1 }] }, { id: 2, categories: [{ name: "Category 4", count: 1 }, { name: "Category 5", count: 2 }, { name: "Category 6", count: 1 }] }, { id: 3, categories: [{ name: "Category 5", count: 1 }] }];
console.log(filterByCategories(products, ["Category 5"])); [{id: 2}, {id: 3}]
console.log(filterByCategories(products, ["Category 5", "Category 4"])); [{id: 2}]

Mapping an array of objects containing an empty array as property ignores the whole object

I have an array of objects -
let initialArr = [
{
"id": 1,
"name": "product name",
"product_details": [
{
"id": 1,
"details": "some details"
}
],
"subscriptions": [
{
"id": 1,
"subs": "7 days"
},
{
"id": 2,
"subs": "15 days"
}
]
},
{
"id": 2,
"name": "product name 2",
"product_details": [
{
"id": 2,
"details": "some details 2"
}
],
"subscriptions": [
{
"id": 1,
"subs": "7 days"
},
{
"id": 2,
"subs": "15 days"
}
]
},
{
"id": 3,
"name": "product name 3",
"product_details": [
{
"id": 3,
"details": "some details 3"
}
],
"subscriptions": []
}
]
This is what I want to achieve -
[
{
"id": 1,
"name": "product name",
"detailsId" : 1,
"details": "some details"
"subsId": 1,
"subs": "7 days"
},
{
"id": 1,
"name": "product name",
"detailsId" : 1,
"details": "some details"
"subsId": 2,
"subs": "15 days"
},
{
"id": 2,
"name": "product name 2",
"detailsId" : 2,
"details": "some details 2"
"subsId": 1,
"subs": "7 days"
},
{
"id": 2,
"name": "product name 2",
"detailsId" : 2,
"details": "some details 2"
"subsId": 2,
"subs": "15 days"
},
{
"id": 3,
"name": "product name 3",
"detailsId" : 3,
"details": "some details 3"
}
]
This is what I have done -
initialArr.map(e => {
e.product_details.map(p =>{
e.subscriptions.map(s => {
newArr.push({
id: e.id,
name: e.name,
detailsId: p.id,
details: p.details,
subsId: s.id,
subs:s.subs
});
});
})
})
This works if subscriptions array is not empty. If for some product, subscriptions array is empty, then that product is not pushed into the array. In I am unable to figure out how to solve it.
3rd product is not pushed in the new array. This is what I get -
[
{
"id": 1,
"name": "product name",
"detailsId" : 1,
"details": "some details"
"subsId": 1,
"subs": "7 days"
},
{
"id": 1,
"name": "product name",
"detailsId" : 1,
"details": "some details"
"subsId": 2,
"subs": "15 days"
},
{
"id": 2,
"name": "product name 2",
"detailsId" : 2,
"details": "some details 2"
"subsId": 1,
"subs": "7 days"
},
{
"id": 2,
"name": "product name 2",
"detailsId" : 2,
"details": "some details 2"
"subsId": 2,
"subs": "15 days"
}
]
Note: Although the same product is repeated twice in the new array, but this is the requirement - products according to "subs" property of subscriptions array.
Supposing i had more arrays e.g. 'Customizations', 'Orders', etc. besides 'Subscriptions' and i want those arrays' data also to be pushed, is this the correct way to do for multiple arrays?
Assuming array product_details has allways 1 element with it's data this is a sollution.
Using Array#reduce to accumulate your new result-array. Creating foreach element a new temp-object with the data for all of it. If the subscriptions-array is empty push this temp-object to your accumulated result-array. Otherwise use Array#forEach to iterate over your subscriptions. For every subscription use Object.assign to make a copy of your temp-object. Add to this the subscription-data and push it to the result-array.
const initialArr = [{ id: 1, name: "product name", product_details: [{ id: 1, details: "some details" }], subscriptions: [{ id: 1, subs: "7 days" }, { id: 2, subs: "15 days" }] }, { id: 2, name: "product name 2", product_details: [{ id: 2, details: "some details 2" }], subscriptions: [{ id: 1, subs: "7 days" }, { id: 2, subs: "15 days" }] }, { id: 3, name: "product name 3", product_details: [{ id: 3, details: "some details 3" }], subscriptions: [] }];
let res = initialArr.reduce((acc, cur) => {
let temp = {
id: cur.id,
name: cur.name,
detailsId: cur.product_details[0].id,
details: cur.product_details[0].details
}
if (!cur.subscriptions.length)
acc.push(temp);
else {
cur.subscriptions.forEach(subs => {
let tempSub = Object.assign({}, temp);
tempSub.subsId = subs.id;
tempSub.subs = subs.subs;
acc.push(tempSub);
})
}
return acc;
}, []);
console.log(res);
Here a version without reduce and instead forEach:
const initialArr = [{ id: 1, name: "product name", product_details: [{ id: 1, details: "some details" }], subscriptions: [{ id: 1, subs: "7 days" }, { id: 2, subs: "15 days" }] }, { id: 2, name: "product name 2", product_details: [{ id: 2, details: "some details 2" }], subscriptions: [{ id: 1, subs: "7 days" }, { id: 2, subs: "15 days" }] }, { id: 3, name: "product name 3", product_details: [{ id: 3, details: "some details 3" }], subscriptions: [] }];
let acc = [];
initialArr.forEach(cur => {
let temp = {
id: cur.id,
name: cur.name,
detailsId: cur.product_details[0].id,
details: cur.product_details[0].details
}
if (!cur.subscriptions.length)
acc.push(temp);
else {
cur.subscriptions.forEach(subs => {
let tempSub = Object.assign({}, temp);
tempSub.subsId = subs.id;
tempSub.subs = subs.subs;
acc.push(tempSub);
})
}
});
console.log(acc);
You could check the length of subscription and return an object instead of mapping the array.
const
data = [{ id: 1, name: "product name", product_details: [{ id: 1, details: "some details" }], subscriptions: [{ id: 1, subs: "7 days" }, { id: 2, subs: "15 days" }] }, { id: 2, name: "product name 2", product_details: [{ id: 2, details: "some details 2" }], subscriptions: [{ id: 1, subs: "7 days" }, { id: 2, subs: "15 days" }] }, { id: 3, name: "product name 3", product_details: [{ id: 3, details: "some details 3" }], subscriptions: [] }],
result = data.flatMap(({ product_details: [{ id: detailsId, details }], subscriptions, ...o }) => subscriptions.length
? subscriptions.map(({ id: subsId, subs }) => ({ ...o, detailsId, details, subsId, subs }))
: ({ ...o, detailsId, details })
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
you need to deal with the case explicitly:
if (e.subscriptions.length === 0) {
newArr.push({ ... }
} else {
e.subscriptions.map(...)
}
also you should use forEach instead of map.

Sorting values in array of objects within array of objects

I'd like to sort through all the itemNames and add all the appropriate quantities together to be able to determine which items were ordered the most.
Here is the array of objects below. I want to try to filter and map through the array of objects and list out the itemName and appropriate totaled quantity for each one, just not sure how to chain together.
function OrderRepository() {
return orderLines.filter((itemName) => {
orderLines.map((quantity) => {
return
}
}
}
Provided array of objects
OrderRepository.prototype.getYesterdaysOrders = function getYesterdaysOrders() {
var yesterdaysOrders = [
{
id: 1,
orderLines: [
{ itemName: "Item 01", quantity: 1 },
{ itemName: "Item 02", quantity: 3 },
{ itemName: "Item 03", quantity: 25 },
{ itemName: "Item 04", quantity: 12 },
],
},
{
id: 2,
orderLines: [
{ itemName: "Item 01", quantity: 1 },
{ itemName: "Item 08", quantity: 42 },
{ itemName: "Item 09", quantity: 13 },
{ itemName: "Item 12", quantity: 37 },
],
},
{
id: 3,
orderLines: [
{ itemName: "Item 12", quantity: 16 },
],
},
{
id: 4,
orderLines: [
{ itemName: "Item 10", quantity: 11 },
{ itemName: "Item 11", quantity: 10 },
],
},
{
id: 5,
orderLines: [
{ itemName: "Item 06", quantity: 7 },
{ itemName: "Item 07", quantity: 2 },
{ itemName: "Item 12", quantity: 14 },
],
},
{
id: 6,
orderLines: [
{ itemName: "Item 05", quantity: 17 },
],
},
{
id: 7,
orderLines: [
{ itemName: "Item 03", quantity: 5 },
{ itemName: "Item 07", quantity: 2 },
],
},
{
id: 8,
orderLines: [
{ itemName: "Item 02", quantity: 13 },
{ itemName: "Item 07", quantity: 7 },
{ itemName: "Item 09", quantity: 2 },
],
},
{
id: 9,
orderLines: [
{ itemName: "Item 01", quantity: 4 },
{ itemName: "Item 06", quantity: 17 },
{ itemName: "Item 07", quantity: 3 },
],
},
{
id: 10,
orderLines: [
{ itemName: "Item 11", quantity: 12 },
{ itemName: "Item 12", quantity: 1 },
],
},
];
return yesterdaysOrders;
};
Desired result
{ itemName: "Item 01", quantity: 6 }
{ itemName: "Item 02", ...... }
I'd like the itemName in order with the totaled quantity listed for that item. So the total number of times Item 01 was ordered yesterday was 6.
You could count the items with the help of a Map and render the wanted result as an array.
var data = [{ id: 1, orderLines: [{ itemName: "Item 01", quantity: 1 }, { itemName: "Item 02", quantity: 3 }, { itemName: "Item 03", quantity: 25 }, { itemName: "Item 04", quantity: 12 }] }, { id: 2, orderLines: [{ itemName: "Item 01", quantity: 1 }, { itemName: "Item 08", quantity: 42 }, { itemName: "Item 09", quantity: 13 }, { itemName: "Item 12", quantity: 37 }] }, { id: 3, orderLines: [{ itemName: "Item 12", quantity: 16 }] }, { id: 4, orderLines: [{ itemName: "Item 10", quantity: 11 }, { itemName: "Item 11", quantity: 10 }] }, { id: 5, orderLines: [{ itemName: "Item 06", quantity: 7 }, { itemName: "Item 07", quantity: 2 }, { itemName: "Item 12", quantity: 14 }] }, { id: 6, orderLines: [{ itemName: "Item 05", quantity: 17 }] }, { id: 7, orderLines: [{ itemName: "Item 03", quantity: 5 }, { itemName: "Item 07", quantity: 2 }] }, { id: 8, orderLines: [{ itemName: "Item 02", quantity: 13 }, { itemName: "Item 07", quantity: 7 }, { itemName: "Item 09", quantity: 2 }] }, { id: 9, orderLines: [{ itemName: "Item 01", quantity: 4 }, { itemName: "Item 06", quantity: 17 }, { itemName: "Item 07", quantity: 3 }] }, { id: 10, orderLines: [{ itemName: "Item 11", quantity: 12 }, { itemName: "Item 12", quantity: 1 }] }],
result = Array.from(
data.reduce((m, { orderLines }) => {
orderLines.forEach(({ itemName, quantity }) => m.set(itemName, (m.get(itemName) || 0) + quantity));
return m;
}, new Map),
([itemName, quantity]) => ({ itemName, quantity })
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This is what you are looking for:
var hashmap = {}
for(var each of yesterdaysOrders) {
for(var one of each['orderLines']) {
if (one['itemName'] in hashmap) {
hashmap[one['itemName']] += one['quantity']
} else {
hashmap[one['itemName']] = one['quantity']
}
}
}
You can use JavaScript's reduce() method to do that.
let result = yesterdaysOrders.reduce((arr, currentValue) => {
currentValue.orderLines.forEach(order => {
const index = arr.findIndex(item => item.itemName === order.itemName);
if (index === -1) {
arr.push(order);
} else {
arr[index].quantity += order.quantity;
}
});
return arr;
}, []);
And sort the resultant array using Array.sort().
// Sorting on item name in ascending order.
result.sort((a, b) => {
if (a.itemName < b.itemName) {
return -1;
} else if (a.itemName > b.itemName) {
return 1;
} else {
return 0;
}
});
Demo:
var yesterdaysOrders = [
{
id: 1,
orderLines: [
{ itemName: "Item 01", quantity: 1 },
{ itemName: "Item 02", quantity: 3 },
{ itemName: "Item 03", quantity: 25 },
{ itemName: "Item 04", quantity: 12 },
],
},
{
id: 2,
orderLines: [
{ itemName: "Item 01", quantity: 1 },
{ itemName: "Item 08", quantity: 42 },
{ itemName: "Item 09", quantity: 13 },
{ itemName: "Item 12", quantity: 37 },
],
},
{
id: 3,
orderLines: [
{ itemName: "Item 12", quantity: 16 },
],
},
{
id: 4,
orderLines: [
{ itemName: "Item 10", quantity: 11 },
{ itemName: "Item 11", quantity: 10 },
],
},
{
id: 5,
orderLines: [
{ itemName: "Item 06", quantity: 7 },
{ itemName: "Item 07", quantity: 2 },
{ itemName: "Item 12", quantity: 14 },
],
},
{
id: 6,
orderLines: [
{ itemName: "Item 05", quantity: 17 },
],
},
{
id: 7,
orderLines: [
{ itemName: "Item 03", quantity: 5 },
{ itemName: "Item 07", quantity: 2 },
],
},
{
id: 8,
orderLines: [
{ itemName: "Item 02", quantity: 13 },
{ itemName: "Item 07", quantity: 7 },
{ itemName: "Item 09", quantity: 2 },
],
},
{
id: 9,
orderLines: [
{ itemName: "Item 01", quantity: 4 },
{ itemName: "Item 06", quantity: 17 },
{ itemName: "Item 07", quantity: 3 },
],
},
{
id: 10,
orderLines: [
{ itemName: "Item 11", quantity: 12 },
{ itemName: "Item 12", quantity: 1 },
],
},
];
let result = yesterdaysOrders.reduce((arr, currentValue) => {
currentValue.orderLines.forEach(order => {
const index = arr.findIndex(item => item.itemName === order.itemName);
if (index === -1) {
arr.push(order);
} else {
arr[index].quantity += order.quantity;
}
});
return arr;
}, []);
// Sorting on item name in ascending order.
result.sort((a, b) => {
if (a.itemName < b.itemName) {
return -1;
} else if (a.itemName > b.itemName) {
return 1;
} else {
return 0;
}
});
console.log(result);

Need help in Looping through 2 Nested Arrays in Javascript/AngularJS and do Comparison

I need to compare two arrays and push elements to one array , if none of the objects in that array match the second array.
Please find my JSON's below:
Array 1:
"[{
"carrierName":"A",
"id":7,
"active":true
"subList":[{
"active":false,
"carrierServiceId":"19",
"locationPrimaryContactName":"ABC 4",
"locationPrimaryContactNumber":"1111",
"locationStateCode":"NJ",
"locationZipcode":"56324",
"name":"A 4"}
,
{
"active":true,
"carrierServiceId":"20",
"locationPrimaryContactName":"ABC 1",
"locationPrimaryContactNumber":"1111",
"locationStateCode":"NJ",
"locationZipcode":"56324",
"name":"A 1"
},
{
"active":true,
"carrierServiceId":"21",
"locationPrimaryContactName":"ABC 2",
"locationPrimaryContactNumber":"1111",
"locationStateCode":"NJ",
"locationZipcode":"56324",
"name":"A 2"},
{
"active":true,
"carrierServiceId":"22",
"id":1001,
"locationPrimaryContactName":"ABC 3",
"locationPrimaryContactNumber":"1111",
"locationStateCode":"NJ",
"locationZipcode":"56324",
"name":"A 3"
}
]
}
]"
Array 2:
"[{"subList":[
{
"active":true,
"code":"20",
"id":0,
"locationPrimaryContactName":"ABC 1",
"locationPrimaryContactNumber":"1111",
"name":"A 1",
},
{
"active":true,
"code":"21",
"id":0,
"locationPrimaryContactName":"ABC 2",
"locationPrimaryContactNumber":"1111",
"name":"A 2",
},
{
"active":true,
"code":"22",
"id":0,
"locationPrimaryContactName":"ABC 3",
"locationPrimaryContactNumber":"1111",
"name":"A 3",
},
{
"active":true,
"code":"19",
"id":0,
"locationPrimaryContactName":"ABC 4",
"locationPrimaryContactNumber":"1111",
"name":"A 4",
}
],
"active":false,
"id":7,
"name":"A",
},
{
"subList":[
{
"active":true,
"code":"7",
"id":0,
"locationPrimaryContactName":"DEF 1",
"locationPrimaryContactNumber":"2222",
"name":"B 1",
},
{
"active":true,
"code":"8",
"id":0,
"locationPrimaryContactName":"DEF 2",
"locationPrimaryContactNumber":"2222",
"name":"B 2",
},
{
"active":true,
"code":"9",
"id":0,
"locationPrimaryContactName":"DEF 3",
"locationPrimaryContactNumber":"2222",
"name":"B 3",
}
],
"active":false,
"id":8,
"name":"B",
},
{
"subList":[
{
"active":true,
"code":"10",
"locationPrimaryContactName":"GHI 1",
"locationPrimaryContactNumber":"3333",
"name":"C 1",
}
],
"active":false,
"id":9,
"name":"C",
},
{
"subList":[
],
"active":false,
"id":10,
"name":"D",
}
]"
Here if you see, the common fields are id, sublist.carrierServiceId in Array 1 & subList.code in Array 2.
My requirement is that I need to loop through Array 1 and Array 2 and add the elements from Array 2 to Array 1, if it does not exist it Array 1. When adding, need to check the "subList" array as well for any particular "id" in Array 2 and if those exist in Array 1, they too should not be added.
Request any expert help on this. Please let me know if the query needs more clarity.
If I understand it correct, the you need to get all elements of array 2 into array 1 at the right place.
This works with a reference to the given objects and creates a new one if necessary.
var array1 = [{ carrierName: "A", id: 7, active: true, subList: [{ active: false, carrierServiceId: "19", locationPrimaryContactName: "ABC 4", locationPrimaryContactNumber: "1111", locationStateCode: "NJ", locationZipcode: "56324", name: "A 4" }, { active: true, carrierServiceId: "20", locationPrimaryContactName: "ABC 1", locationPrimaryContactNumber: "1111", locationStateCode: "NJ", locationZipcode: "56324", name: "A 1" }, { active: true, carrierServiceId: "21", locationPrimaryContactName: "ABC 2", locationPrimaryContactNumber: "1111", locationStateCode: "NJ", locationZipcode: "56324", name: "A 2" }, { active: true, carrierServiceId: "22", id: 1001, locationPrimaryContactName: "ABC 3", locationPrimaryContactNumber: "1111", locationStateCode: "NJ", locationZipcode: "56324", name: "A 3" }] }],
array2 = [{ subList: [{ active: true, code: "20", id: 0, locationPrimaryContactName: "ABC 1", locationPrimaryContactNumber: "1111", name: "A 1", }, { active: true, code: "21", id: 0, locationPrimaryContactName: "ABC 2", locationPrimaryContactNumber: "1111", name: "A 2", }, { active: true, code: "22", id: 0, locationPrimaryContactName: "ABC 3", locationPrimaryContactNumber: "1111", name: "A 3", }, { active: true, code: "19", id: 0, locationPrimaryContactName: "ABC 4", locationPrimaryContactNumber: "1111", name: "A 4", }], active: false, id: 7, name: "A", }, { subList: [{ active: true, code: "7", id: 0, locationPrimaryContactName: "DEF 1", locationPrimaryContactNumber: "2222", name: "B 1", }, { active: true, code: "8", id: 0, locationPrimaryContactName: "DEF 2", locationPrimaryContactNumber: "2222", name: "B 2", }, { active: true, code: "9", id: 0, locationPrimaryContactName: "DEF 3", locationPrimaryContactNumber: "2222", name: "B 3", }], active: false, id: 8, name: "B", }, { subList: [{ active: true, code: "10", locationPrimaryContactName: "GHI 1", locationPrimaryContactNumber: "3333", name: "C 1", }], active: false, id: 9, name: "C", }, { subList: [], active: false, id: 10, name: "D" }],
reference = {};
array1.forEach(function (a) {
if (!reference[a.id]) {
reference[a.id] = { data: a, children: {} };
}
a.subList.forEach(function (b) {
reference[a.id].children[b.carrierServiceId] = b;
});
});
array2.forEach(function (a) {
if (!reference[a.id]) {
reference[a.id] = { data: { carrierName: a.name, id: a.id, active: a.active, subList: [] }, children: {} };
array1.push(reference[a.id].data);
}
a.subList.forEach(function (b) {
if (!reference[a.id].children[b.code]) {
reference[a.id].children[b.code] = {
active: b.active,
carrierServiceId: b.code,
locationPrimaryContactName: b.locationPrimaryContactName,
locationPrimaryContactNumber: b.locationPrimaryContactNumber,
// locationStateCode: b.locationPrimaryContactNumber,
// locationZipcode: b.locationZipcode,
name: b.name
};
reference[a.id].data.subList.push(reference[a.id].children[b.code]);
}
});
});
console.log(array1);

AngularJS and JSON Array

I am trying to arrange the existed JSON Array following as below by using AngularJS filter such as $filter, but it is failing.
{
{
name: "name 1",
label: "A",
},
{
name: "name 2",
label: "A",
},
{
name: "name 3",
label: "B",
},
{
name: "name 4",
label: "B",
},
{
name: "name 5",
label: "B",
},
{
name: "name 6",
label: "C",
},
{
name: "name 7",
label: "C",
},
{
name: "name 8",
label: "C",
},
{
name: "name 9",
label: "D",
}
}
What I want is to arrange this array to new one following as below.
{
"A" : {
{
name: "name 1",
label: "A",
},
{
name: "name 2",
label: "A",
},
},
"B" : {
{
name: "name 3",
label: "B",
},
{
name: "name 4",
label: "B",
},
{
name: "name 5",
label: "B",
},
},
"C" : {
{
name: "name 6",
label: "C",
},
{
name: "name 7",
label: "C",
},
{
name: "name 8",
label: "C",
},
},
"D" : {
{
name: "name 9",
label: "D",
}
}
}
How can I get the new array using angularJS?
If you were using lodash, you could utilise _.groupBy function for this:
var grouppedArray = _.groupBy(myArray, function(i){
return i.label;
})
To extract only labels you could smth like this
var uniqueLables = [];
angular.forEach(myArray, function(obj){
if(uniqueLables.indexOf(obj.label) == -1) uniqueLables.push(obj.label)
})
try this
var result = {}
angular.forEach(jsonData, function(obj){
if(!result.hasOwnProperty(obj.label) result[obj.label] = []
result[obj.label].push(obj)
})
console.log(result)

Categories