Deleting an entry from a JSON array [duplicate] - javascript

This question already has answers here:
remove objects from array by object property
(15 answers)
Closed 4 years ago.
How can I delete a specific element (eg: using its id) from a JSON array?
A delete button will perform this task, passing its id.
For example, how to delete item with id = 2 :
Note: id number 2 can be in an array index of 10 or 20.
"id": 2, "date": "27 Mar 2018", "name": "name 2", "type":
"meeting"
var id = 1;
var events = [{
"id": id++,
"date": "26 Mar 2018",
"name": "name 1",
"type": "task"
},
{
"id": id++,
"date": "27 Mar 2018",
"name": "name 2",
"type": "meeting"
},
{
"id": id++,
"date": "27 Mar 2018",
"name": "name 3",
"type": "meeting"
}
];
events.push({
"id": id++,
"date": "25 Mar 2018",
"name": "name 4",
"type": "meeting"
});

You can do like below
var events = [{
"id": 1,
"date": "26 Mar 2018",
"name": "name 1",
"type": "task"
},
{
"id": 10,
"date": "27 Mar 2018",
"name": "name 2",
"type": "meeting"
},
{
"id": 15,
"date": "27 Mar 2018",
"name": "name 3",
"type": "meeting"
}
];
let entry_to_delete=events.find(e => e.id === 10);
events.splice(events.indexOf(entry_to_delete),1);
console.log(events);

Related

How to determine intersect objects in json array with javascript?

I have json data like this:
[{
"Id": 1,
"Name": "Test 1",
"Time": {
"start": "22:00",
"end": "22:30",
"duration": 30
}
}, {
"Id": 2,
"Name": "Test 2",
"Time": {
"start": "22:05",
"end": "22:35",
"duration": 30
}
}, {
"Id": 3,
"Name": "Test 3",
"Time": {
"start": "23:25",
"end": "23:40",
"duration": 15
}
},{
"Id": 4,
"Name": "Test 4",
"Time": {
"start": "22:15",
"end": "22:50",
"duration": 15
}
}
]
And i want get result like this, determine which intersect by Time:
[
["Test 1", "Test 2", "Test 4"],
["Test 3"]
]
I have solution, but it's too complicated and i use 4 loops inside each other
If there is an easier solution, please suggest, thanks!
Try aggregation, I am not sure this will work exact as per your requirement,
$addFields add new field startHour, that splits string hour and minute from string, using $split, and $arrayElemAt return first element means hour
$group by startHour and make array of Name
db.collection.aggregate([
{
$addFields: {
startHour: {
$arrayElemAt: [{ $split: ["$Time.start", ":"] }, 0]
}
}
},
{
$group: {
_id: "$startHour",
Name: { $push: "$Name" }
}
}
])
Playground
Result:
[
{
"Name": ["Test 1","Test 2","Test 4"],
"_id": "22"
},
{
"Name": ["Test 3"],
"_id": "23"
}
]

JSON manipulation - count keys with same value, create new object with count as value

I want to count the JSON nodes having the same date, and create a new object with the date as the key and the count as the value.
So, using either jQuery or vanilla JS, how would I turn this:
[
{
"date": "January 1"
},
{
"date": "January 1"
},
{
"date": "January 1"
},
{
"date": "January 1"
},
{
"date": "February 14"
},
{
"date": "February 14"
},
{
"date": "July 8"
},
{
"date": "July 8"
},
{
"date": "July 8"
},
{
"date": "December 11"
}
]
Into this:
[
{
"January 1": 4 // Number or String "4", doesn't matter
},
{
"February 14": 2
},
{
"July 8": 3
},
{
"December 11": 1
}
]
Try something like this.
const data = [
{
"date": "January 1"
},
{
"date": "January 1"
},
{
"date": "January 1"
},
{
"date": "January 1"
},
{
"date": "February 14"
},
{
"date": "February 14"
},
{
"date": "July 8"
},
{
"date": "July 8"
},
{
"date": "July 8"
},
{
"date": "December 11"
}
]
let counter = {}
data.forEach(function(obj) {
var key = obj.date
counter[key] = (counter[key] || 0) + 1
})
console.log(counter)

Nested ngFor only returns last item on inner ngFor

I am trying to loop through firebase RTDB reference to retrieve a list and then use those results in a subsequent firestore query. the console logs the correct data but my code only displays the last item in the loop in the inside ngFor. Any help would be appreciated. Thanks
this.ref = firebase.database().ref('stations/');
this.ref.on('value', resp => {
this.infos = [];
this.infos = snapshotToArray(resp);
});
const snapshotToArray = snapshot => {
let returnArr = [];
snapshot.forEach(childSnapshot => {
let item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item.StationtName);
let sku = item.StationtName;
this.queues = this.afs.collection('projects', ref => ref.where('station', '==', item.StationtName)).valueChanges()
});
return returnArr;
}
html:
<div *ngFor="let info of infos">
{{info}}
<div *ngFor="let queue of queues | async">
<ion-button> {{queue.SKU}}</ion-button>
</div>
</div>
json and new error:
ERROR Error: Cannot find a differ supporting object '[
{
"SKU": "908897",
"buyerEmail": "m",
"comments": "c",
"createdAt": 1550285024451,
"queue": 1,
"station": "The Warehouse",
"timeTest": "Fri Feb 15 2019",
"type": "Project"
}
]' of type 'string'. NgFor only supports binding to Iterables such as Arrays.
this.infos:
["Lathe", "Press 1", "Press 2", "Mill 1", "Mill 2", "Ready", "Plasma", "Grinding", "Grinding", "Flange shop", "the office", "The Warehouse"]
added an .subscribe() to this.queues and got the correct info logged to the console on every loop. The associated projects for each station are printed to the console. Here is one of them;
["09987", "66553", "3", "98774", "4", "987654321", "1", "6533343434343"]
these are all SKU's that are associated with each station.
Here is the subscribe code I added to get the value of the observable, now Im getting another error though:
.subscribe(data=>{
console.log(data);
this.items = data.map(function (obj) {
return obj.SKU;
});
console.log(this.items);
// this.stationArr.push(this.item);
})
The error I'm getting now is:
Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
And this in the the chrome inspector:
<!--bindings={
"ng-reflect-ng-for-of": null
}-->
current output:
Lathe
----- 908897
Press 1
----- 908897
Press 2
----- 908897
Mill 1
----- 908897
Mill 2
----- 908897
Ready
----- 908897
Plasma
----- 908897
Grinding
----- 908897
Grinding
----- 908897
Flange shop
----- 908897
the office
----- 908897
The Warehouse
----- 908897
desired output:
Lathe
----- 908897
Press 1
----- 123432,5476344
Press 2
----- empty
Mill 1
----- 0987654, 7777777, 673654
Mill 2
----- 12321
Ready
----- 909090990, 878787878, 67767
etc.
each station has a SKU associated, but my code displays the same one for each station.
json file:
[{
"id": "0rikFyAEt4Zg83sPeUNG",
"SKU": "88",
"buyerEmail": "",
"comments": "",
"createdAt": 1550297319125,
"queue": 1,
"station": "Press 1",
"timeTest": "Sat Feb 16 2019",
"type": "Project"
}, {
"id": "1UJftXBqdmvjwJAs2XO5",
"SKU": "77777e7e7",
"buyerEmail": "b",
"comments": "c",
"createdAt": 1550291447696,
"queue": 1,
"station": "Lathe",
"timeTest": "Fri Feb 15 2019",
"type": "Project"
}, {
"id": "1aFkV5z0JBzfii0edQCd",
"SKU": "911111111",
"buyerEmail": "matt#duhon.com",
"comments": "comment",
"createdAt": 1550286952568,
"queue": 1,
"station": "Grinding",
"stations": ["Addy"],
"timeTest": "Fri Feb 15 2019",
"type": "Project"
}, {
"id": "5BylWSmtH02v8oCq7T2B",
"SKU": "123456789",
"buyerEmail": "MAtts",
"comments": "comment",
"createdAt": 1550372243065,
"queue": 1,
"station": "Press 1",
"timeTest": "Sat Feb 16 2019",
"type": "Project"
}, {
"id": "BVNaMjK5oqSslnfE6Uar",
"SKU": "11111111",
"buyerEmail": "",
"comments": "",
"createdAt": 1550290392880,
"queue": 1,
"station": "Mill",
"timeTest": "Fri Feb 15 2019",
"type": "Project"
}, {
"id": "HvxQF4suTBaiCwpWgf9D",
"SKU": "908897",
"buyerEmail": "m",
"comments": "c",
"createdAt": 1550285024451,
"queue": 1,
"station": "The Warehouse",
"timeTest": "Fri Feb 15 2019",
"type": "Project"
}, {
"id": "KfJ4qvVyDzVwFxIeMRzM",
"SKU": "09987",
"buyerEmail": "",
"comments": "",
"createdAt": 1550286034246,
"queue": 1,
"station": "Ready",
"timeTest": "Fri Feb 15 2019",
"type": "Project"
}, {
"id": "MrrioE5IHpImz52qnHW5",
"SKU": "1211221",
"buyerEmail": "",
"comments": "",
"createdAt": 1550290371569,
"queue": 1,
"station": "Lathe",
"timeTest": "Fri Feb 15 2019",
"type": "Project"
}, {
"id": "TczmkayGuWonT6SQZf6F",
"SKU": "3",
"buyerEmail": "",
"comments": "3 years old yo!",
"createdAt": 1550298020154,
"queue": 1,
"station": "Ready",
"timeTest": "Sat Feb 16 2019",
"type": "Project"
}, {
"id": "ZspOz31o0uYT0Msull5J",
"SKU": "909987",
"buyerEmail": "matt#duhon.com",
"comments": "comment",
"createdAt": 1550286926441,
"queue": 1,
"station": "Packaging",
"timeTest": "Fri Feb 15 2019",
"type": "Project"
}, {
"id": "hXC1uswgbW1UVTfVD96k",
"SKU": "98774",
"buyerEmail": "matt#duhon.com",
"comments": "comments",
"createdAt": 1550296878271,
"queue": 1,
"station": "Ready",
"timeTest": "Sat Feb 16 2019",
"type": "Project"
}, {
"id": "jeR8wCiPdCwObZvajT04",
"SKU": "4",
"buyerEmail": "matt",
"comments": "comments",
"createdAt": 1550298181612,
"queue": 1,
"station": "Ready",
"timeTest": "Sat Feb 16 2019",
"type": "Project"
}, {
"id": "lx2Hh3rpQ1rLkGHAgEzo",
"SKU": "987654321",
"buyerEmail": "yomama",
"comments": "com mints",
"createdAt": 1550296669267,
"queue": 1,
"station": "Ready",
"timeTest": "Fri Feb 15 2019",
"type": "Project"
}, {
"id": "qAYSdYYC2wxBwYDYI71T",
"SKU": "1",
"buyerEmail": "",
"comments": "",
"createdAt": 1550297026128,
"queue": 1,
"station": "Ready",
"timeTest": "Sat Feb 16 2019",
"type": "Project"
}, {
"id": "sBXhW6lPaYtUn4fz5Gsf",
"SKU": "6533343434343",
"buyerEmail": "MAtt",
"comments": "Comment",
"createdAt": 1550372086063,
"queue": 1,
"station": "Ready",
"timeTest": "Sat Feb 16 2019",
"type": "Project"
}]
As per you code check this Demo code where you can see the nested *ngFor
<ul>
<li *ngFor="let info of infos">{{info}}
<ol *ngFor="let queue of queues | async">{{queue.SKU}}</ol>
</li>
</ul>

How to eliminate multiple iteration

Following code gets the result below in a way that multiple iterations required. I wonder what would be the way to make it happen in a single or less iterations. Thanks in advance.
var input = [{
"ActiveMembers": [{
"Id": 101,
"Name": "alpha"
}, {
"Id": 102,
"Name": "bravo"
}],
"Contents": [{
"Id": 2001,
"RowId": "517",
"Time": "19 Jan 2017",
"ViewCount": 1124
}, {
"Id": 2002,
"RowId": "518",
"Time": "Today, 07:02 PM",
"ViewCount": 62
}],
"TotalUsers": 3,
"UsersDetails": "2 members, 1 anonymous users"
}, {
"ActiveMembers": [{
"Id": 101,
"Name": "alpha"
}, {
"Id": 103,
"Name": "charlie"
}, {
"Id": 104,
"Name": "delta"
}, {
"Id": 105,
"Name": "bravo"
}],
"Contents": [{
"Id": 2002,
"RowId": "519",
"Time": "27 Jun 2017",
"ViewCount": 4833
}, {
"Id": 2041,
"RowId": "525",
"Time": "17 Feb 2015",
"ViewCount": 24491
}],
"TotalUsers": 23,
"UsersDetails": "4 members, 19 anonymous users"
}];
var contents = Array.prototype.concat.apply([], input.map(i => i.Contents));
var activeMembers = _.uniqBy(Array.prototype.concat.apply([], input.map(i => i.ActiveMembers)), (i) => i.Id);
var totalUsers = number = _.sumBy(input, (i) => i.TotalUsers);
var userDetails = string = input.map(i => i.UsersDetails).join(' ; ');
const result = new Object();
result.Contents = contents;
result.ActiveMembers = activeMembers;
result.TotalUsers = totalUsers;
result.UserDetails = userDetails;
console.log(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Result
{
"ActiveMembers": [
{
"Id": 101,
"Name": "alpha"
},
{
"Id": 102,
"Name": "bravo"
},
{
"Id": 103,
"Name": "charlie"
},
{
"Id": 104,
"Name": "delta"
},
{
"Id": 105,
"Name": "bravo"
}
],
"Contents": [
{
"Id": 2001,
"RowId": "517",
"Time": "19 Jan 2017",
"ViewCount": 1124
},
{
"Id": 2002,
"RowId": "518",
"Time": "Today, 07:02 PM",
"ViewCount": 62
},
{
"Id": 2002,
"RowId": "519",
"Time": "27 Jun 2017",
"ViewCount": 4833
},
{
"Id": 2041,
"RowId": "525",
"Time": "17 Feb 2015",
"ViewCount": 24491
}
],
"TotalUsers": 26,
"UsersDetails": "2 members, 1 anonymous users;4 members, 19 anonymous users"
}
Aggregate the data in a single iteration.
let ActiveMembers = [];
let Contents = [];
let TotalUsers = 0;
let UserDetails = [];
input.forEach((item) => {
ActiveMembers = ActiveMembers.concat(item.ActiveMembers);
Contents = Contents.concat(item.Contents);
TotalUsers += item.TotalUsers;
UserDetails.push(item.UsersDetails);
});
const result = {
ActiveMembers: _.uniqBy(ActiveMembers, "Id"),
Contents: Contents,
TotalUsers: TotalUsers,
UserDetails: UserDetails.join(";")
};
console.log(JSON.stringify(result));

underscore.js how to combine 2 collections

I have two collections A and B. ( A,B have the exactly same structure, but different nodes values)
now I'd like to add A into B, with exactly the order: A B and without merging or changing any
nodes inside them. ( just like a joint action) { A } + {B}
I've read the documentation for underscore but couldn't find a proper function which gets this job done.
any idea?
==========update with example ========Sample is simplified from a larger structure, if there are errors please let me know=========
var collection1 = [{
"date": "29 January 2014",
"items": [{
"name": "Jack",
"score": 90,
"title": "programmer"
}, {
"name": "TOM",
"score": 52,
"title": "designer"
}]
}, {
"date": "28 January 2014",
"items": [{
"name": "Jim",
"score": 30,
"title": "driver"
}, {
"name": "William",
"score": 52,
"title": "worker"
}]
}]
var collect2 = [{
"date": "26 January 2014",
"items": [{
"name": "Marry",
"score": 92,
"title": "teacher"
}, {
"name": "TOM",
"score": 52,
"title": "designer"
}]
}]
========expected output==============
[{
"date": "29 January 2014",
"items": [{
"name": "Jack",
"score": 90,
"title": "programmer"
}, {
"name": "TOM",
"score": 52,
"title": "designer"
}]
}, {
"date": "28 January 2014",
"items": [{
"name": "Jim",
"score": 30,
"title": "driver"
}, {
"name": "William",
"score": 52,
"title": "worker"
}]
}, {
"date": "26 January 2014",
"items": [{
"name": "Marry",
"score": 92,
"title": "teacher"
}, {
"name": "TOM",
"score": 52,
"title": "designer"
}]
}]
I think what you are looking for is simply Array.concat
var foo = ['a','b','c'];
var bar = ['d','e','f'];
var all = foo.concat(bar); // ['a','b','c','d','e','f'];
Use Underscore#extend as : _.extend(collection1, collection2);
DEMO
col1 = { aa: 'aa', cc: 'cc' }; col2 = { bb: 'bb', dd: 'dd' };
_.extend(col1, col2)
console.log(col1);
# Prints Object {aa: "aa", cc: "cc", bb: "bb", dd: "dd"}

Categories