how to remove this object from array inside of object in array? - javascript

I am not sure how to form this question, but I will do my best.
I don't know how to remove object by _id from 'list:' part.
So, I have one array, and inside of that array I have list of objects,inside of these objects I have again array with objects, so I want to remove one object from that last array, how I can do that?
Cannot fix it for 2 days, I'm stucked!
Thanks!
[
{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [
{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [
{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
]

Using Vanilla JS:
function findAndRemove(data, id) {
data.forEach(function(obj) { // Loop through each object in outer array
obj.list = obj.list.filter(function(o) { // Filter out the object with unwanted id, in inner array
return o._id != id;
});
});
}
var data = [{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
];
// Empty almost all of list, except middle one
findAndRemove(data, "599a1322bf50847b0972a384");
findAndRemove(data, "599a1322bf50847b0972a386");
findAndRemove(data, "599a12fdbf50847b0972a2a5");
findAndRemove(data, "599a12fdbf50847b0972a2a6");
findAndRemove(data, "599a12fdbf50847b0972a2ab");
console.log(data);
Cleared everything except middle list, just for better visualization.

#Abhijit Kar your one is working perfectly, thanks mate!
How I can later splice this list?
When I was working with objects from first array, I did it like this :
var inventory = jsonArrayList;
for (var i = 0; i < inventory.length; i++) {
if (inventory[i]._id == deleteProductById) {
vm.items.splice(i, 1);
break;
}
}
It would be very helpful, thanks alot!

You can use Array.map and Array.filter to accomplish this. Detailed explanation in comments:
PS: This snippet uses ES6 arrow functions and spread operator
function removeById(arr, id) {
// Array.map iterates over each item in the array,
// and executes the given function on the item.
// It returns an array of all the items returned by the function.
return arr.map(obj => {
// Return the same object, if the list is empty / null / undefined
if (!obj.list || !obj.list.length) return obj;
// Get a new list, skipping the item with the spedified id
const newList = obj.list.filter(val => val._id !== id);
// map function returns the new object with the filtered list
return { ...obj, list: newList };
});
}
const oldArray = <YOUR_ORIGINAL_ARRAY>;
const newArray = removeById(arr, "599a12fdbf50847b0972a2a5");

Related

How to add or update items in this multidimensional JSON?

Let's say we have some houses represented as JSON. Something like this:
[
{
"id": "1",
"code": "1",
"name": "Smith's",
"children": [
{
"id": "",
"code": "11",
"name": "Kitchen",
"children": [
{
"id": "",
"code": "111",
"name": "Sink",
"children": []
}
]
},
{
"id": "",
"code": "12",
"name": "Living Room",
"children": [
{
"id": "",
"code": "121",
"name": "Television",
"children": [
{
"id": "",
"code": "1211",
"name": "Panel buttons",
"children": [
{
"id": "",
"code": "12111",
"name": "Power button",
"children": []
},
{
"id": "",
"code": "12112",
"name": "Colors adjust button",
"children": []
}
]
},
{
"id": "",
"code": "1221",
"name": "Screen",
"children": []
}
]
}
]
}
]
},
{
"id": "2",
"code": "2",
"name": "Taylor's",
"children": [
// Here goes all house places and items like the example above
]
},
{
"id": "1",
"code": "1",
"name": "Wilson's",
"children": [
// Here goes all house places and items like the example above
]
}
]
Take notice that the "code" property, found in each item, is something to represent the "path" until that item, carrying its parents "code" property concatenated with its own position by incremental order. So the code "11" means house 1 and child 1. And 212 would be house 2, child 1, child 2. Also take notice that all items follow the same type. In other words, every item has a children that follows its own type. So, it could be infinite.
Now, I'd like to maintain these structure. Adding items, updating items and so on. Let's say we want to add a carpet in Smith's living room. We would go deep in the structure 2 levels, which are Smith's house (index 0 of the array) and living room (index 1 of the children array). And then add a carpet.
The problem is it won't be 2 levels in all cases. What if I wanted to add a bathroom? It would be level 1, alongside with kitchen in living room (the first children). What if I'd like to add a microwave in the kitchen and add to it buttons, display, etc?
I think I'm a recursive scenario where I have to visit all items and, if it is the one I'm looking to reach at, add/updated it.
I've tried following this example
I couldn't figure it out how to bring it to my case. though.
I appreciate if your contribution is in JavaScript, but feel free to represent it in other language in case you are better in other language =).
There are indeed some questions, like for instance what happens if you have more than 10 items as child and why do you need it?
And what happens if you remove any item on any level? will you recursively start updating all codes?
Nevertheless I gave it a go. In essence what I do in the code is first search for the parent (example: Kitchen) where you want to add it to and then add the new child item (example: Carpet) to it.
The search is a typical recursive search.
The child addition is a typical addition to an array.
For argument's sake I assumed that the fields code always exist and that children is always an array.
// Actual code is underneath the declaration of this array
let houseList = [
{
"id": "1",
"code": "1",
"name": "Smith's",
"children": [
{
"id": "",
"code": "11",
"name": "Kitchen",
"children": [
{
"id": "",
"code": "111",
"name": "Sink",
"children": []
}
]
},
{
"id": "",
"code": "12",
"name": "Living Room",
"children": [
{
"id": "",
"code": "121",
"name": "Television",
"children": [
{
"id": "",
"code": "1211",
"name": "Panel buttons",
"children": [
{
"id": "",
"code": "12111",
"name": "Power button",
"children": []
},
{
"id": "",
"code": "12112",
"name": "Colors adjust button",
"children": []
}
]
},
{
"id": "",
"code": "1221",
"name": "Screen",
"children": []
}
]
}
]
}
]
},
{
"id": "2",
"code": "2",
"name": "Taylor's",
"children": [
// Here goes all house places and items like the example above
]
},
{
"id": "1",
"code": "1",
"name": "Wilson's",
"children": [
// Here goes all house places and items like the example above
]
}
]
addChild(houseList,"11",{name:"Carpet" });
addChild(houseList,"1211",{name: "Volume Up Button"});
addChild(houseList,"1211",{name: "Volume Down Button"});
console.log('new houselist', houseList);
// child is just what you want to add and the parentCode refers to where you want to add it to
function addChild(houseList, parentCode, child) {
let parent = findInHouseList(houseList,parentCode,child);
let amountOfChildren = parent.children.length;
let newCodeName = parentCode +""+ (amountOfChildren+1);
child = {...{id: "", code: newCodeName, children: []}, ...child};
console.log('adding child ', child);
parent.children = [...parent.children, child];
}
function findInHouseList(houseList,code) {
for (let house of houseList) {
let foundElement = findElement(house,code);
if ( foundElement)
return foundElement;
}
}
function findElement(currentElement, code) {
if ( currentElement.code === code)
return currentElement;
if (currentElement.children?.length > 0)
{
for (let child of currentElement.children) {
let foundElement = findElement(child,code);
if ( foundElement)
return foundElement;
}
}
return null;
}
I decided to let the code manage the code names for new children. It seems the easiest.
What you're trying to do is updating a JSON value at a dynamic path.
This function will append a child to the item which holds the specified code.
You may add conditions to check if the item at the code is defined
function appendChild(houses, code, item) {
let path = code.split('')
let o = houses
for (let i = 0; i < path.length; i++) {
let n = path[i] - 1
o = o[n]["children"]
}
o.push(item)
return houses
}
However, you should start your code indexes at 0 and storing them inside the JSON is useless since they are simply the path to reach the item.

Grab multiple properties of a JSON

I'm working with a large JSON file that looks like this:
{
"name": "Superproduct",
"description": "Enjoy this amazing product.",
"brand": "ACME",
"categories": [
"Ball",
"Soccer Ball",
"Beach Ball"
],
"type": "Online product",
"price": 50,
"price_range": "50 - 100",
"image": "someImageURL",
"url": "SomeProductURL",
"free_shipping": true,
"popularity": 10000,
"rating": 2,
"objectID": "1234"
}
I am trying to access every object with the Ball category, so that I can add a discount to that specific item. I realized that every object can have multiple variations of the word Ball in the category array.
Is there a way I can target the word ball in the array, so that I can add that to an array and apply the discount to every product with said criteria?
This is what I have so far, but I'm not sure if this is the best way, or if there's a better way to accomplish what I'm trying to do:
async function setDiscount() {
let discountedRate = 0.5;
fetch('products.json')
.then(res => res.json())
.then(data => {for (let i = 0; i < data.length; i++) {
if (data[i].categories[i] == "Ball") {
data[i].price -= (data[i].price * discountedRate);
}
}});
}
setDiscount();
P.S.: I'm a newbie.
You can simply achieve this by iterating the response array.
Working Demo :
const data = [{
"name": "Superproduct",
"description": "Enjoy this amazing product.",
"brand": "ACME",
"categories": [
"Ball",
"Soccer Ball",
"Beach Ball"
],
"type": "Online product",
"price": 50,
"price_range": "50 - 100",
"image": "someImageURL",
"url": "SomeProductURL",
"free_shipping": true,
"popularity": 10000,
"rating": 2,
"objectID": "1234"
}];
const discountedRate = 0.5;
data.forEach((obj) => {
obj.price = obj.categories.includes('Ball') ? (obj.price * discountedRate) : obj.price
});
console.log(data);

ES6 Filter elements from an array within an array

I currently have 2 arrays. Each array has another array named "url".
{
"entities": [
{
"id": 0,
"companyName": "4-County Electric Power Assn",
"type": "E",
"state": "MS",
"code": "106641MS",
"url": [
{
"title": "4 County Electric",
"link": "http://www.4county.org/",
"href": "http://www.4county.org/"
}
]
},
{
"id": 1,
"companyName": "ACTON WATER DISTRICT OFFICE",
"type": "W",
"state": "MA",
"code": "W1771MA",
"url": [
{
"title": "Home — Acton Water District",
"link": "http://www.actonwater.com/",
"href": "http://www.actonwater.com/"
},
{
"title": "Contact Us — Acton Water District",
"link": "http://www.actonwater.com/customer-service/contact-us",
"href": "http://www.actonwater.com/customer-service/contact-us"
}
]
}
]
}
I'm trying to filter in each url array and remove any item that doesn't match the filter.
I've created a filter that successfully filters out the urls that dont contain the word "contact"
const regex = new RegExp('/contact\\b', 'g');
const companyColumn = db.get(`entities`).value()
const filteredData = companyColumn.map((a ,i) => {
return a.url.filter(({href}) => href.match(regex))
})
and get the response:
[ [],
[ { title: 'Contact Us — Acton Water District',
link: 'http://www.actonwater.com/customer-service/contact-us',
description: 'Office hours are Monday–Friday, 7:30 AM until 4:00 PM (excluding holidays) We \nare located at 693 Massachusetts Avenue, Acton, Ma 01720. Our mailing ...',
href: 'http://www.actonwater.com/customer-service/contact-us' } ] ]
boom. so it works.
But my question is how can I set the first item in the "entities" array to have an empty URL array, while the second "entities" item has only 1 item in it's URL array.
I feel so close...

Checking a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?
You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }

Sorting an array of JavaScript objects by sub array property/value

I have the following data being returned from a server (the structure of this data is something that I do not have control over)...
var data = {
"TrackingResults": [
{
"Name": "Pack One",
"Products": {
"Product": [
{
"ProductName": "Soccer Ball"
},
{
"ProductName": "Tennis Racket"
},
{
"ProductName": "Gold Putter"
}
]
},
"status": "Despatched",
"Location": "Alabama",
"Type": "Parcel"
},
{
"Name": "Pack Two",
"Products": {
"Product": [
{
"ProductName": "Backet Ball Hoop"
},
{
"ProductName": "Base Ball Glove"
}
]
},
"status": "Despatched",
"Location": "Florida",
"Type": "Parcel"
}
]
};
I would like to be able to sort each Tracking Result by the first Product Name. I can't find any code that will sort by a sub array property/value.
You should use the Array.sort method with a custom comparator function:
var resultsComparator = function (res1, res2) {
var prod1 = res1.Products.Product[0].ProductName;
var prod2 = res2.Products.Product[0].ProductName;
return prod1.localeCompare(prod2);
}
This way the ordering is based on the current locale of the web browser. You just pass the function to the sort method:
data.TrackingResults.sort(resultsComparator);
You need to write it manually like: (with the hint on localeCompare from meskobalazs's comment)
var result = data.TrackingResults.sort(function(a,b){
return a.Products.Product[0].ProductName.localeCompare(b.Products.Product[0].ProductName)
});
This should work for sorting TrackingResults

Categories