how to group the data by a field into subarray in JavaScript - javascript

I have an array like below. I want to group this array by day field.
input_array = [{
"name": "alagu",
"day": "monday",
"time": "morning",
"task": "studying"
}, {
"name": "alagu",
"day": "monday",
"time": "evening",
"task": "playing"
}, {
"name": "alagu",
"day": "monday",
"time": "night",
"task": "sleeping"
}, {
"name": "alagu",
"day": "sunday",
"time": "morning",
"task": "playing"
}, {
"name": "alagu",
"day": "sunday",
"time": "evening",
"task": "playing"
}, {
"name": "alagu",
"day": "sunday",
"time": "night",
"task": "sleeping"
}]
I want the result will be like the below array.
result_array = [{
"name": "alagu",
"day": "monday",
"schedule": [
{ "time": "morning", "task": "studying" },
{ "time": "evening", "task": "playing" },
{ "time": "evening", "task": "sleeping" }
]
}, {
"name": "alagu",
"day": "sunday",
"schedule": [
{ "time": "morning", "task": "playing" },
{ "time": "evening", "task": "playing" },
{ "time": "night", "task": "sleeping" }
]
}]
What I mean is I want to group by day and then I have to make sub array schedule having elements of time and task. please help.

For get your required result from sample data by foreach and map functions :
const input_array = [{ "name":"alagu", "day":"monday", "time":"morning", "task":"studying" },
{ "name":"alagu", "day":"monday", "time":"evening", "task":"playing" },
{ "name":"alagu", "day":"monday", "time":"night", "task":"sleeping" },
{ "name":"alagu", "day":"sunday", "time":"morning", "task":"playing" },
{ "name":"alagu", "day":"sunday", "time":"evening", "task":"playing" },
{ "name":"alagu", "day":"sunday", "time":"night", "task":"sleeping" }]
const result = {};
inputArray.forEach(item => {
const { name, day, time, task } = item;
if (!result[day]) {
result[day] = { name, day, schedule: [] };
}
result[day].schedule.push({ time, task });
});
const resultArray = Object.keys(result).map(key => result[key]);
console.log(resultArray);
Result :
[
{
"name":"alagu",
"day":"monday",
"schedule":[
{
"time":"morning",
"task":"studying"
},
{
"time":"evening",
"task":"playing"
},
{
"time":"night",
"task":"sleeping"
}
]
},
{
"name":"alagu",
"day":"sunday",
"schedule":[
{
"time":"morning",
"task":"playing"
},
{
"time":"evening",
"task":"playing"
},
{
"time":"night",
"task":"sleeping"
}
]
}
]

You can use reduce function like this:
const input_array = [{
"name": "alagu",
"day": "monday",
"time": "morning",
"task": "studying"
}, {
"name": "alagu",
"day": "monday",
"time": "evening",
"task": "playing"
}, {
"name": "alagu",
"day": "monday",
"time": "night",
"task": "sleeping"
}, {
"name": "alagu",
"day": "sunday",
"time": "morning",
"task": "playing"
}, {
"name": "alagu",
"day": "sunday",
"time": "evening",
"task": "playing"
}, {
"name": "alagu",
"day": "sunday",
"time": "night",
"task": "sleeping"
}]
const result_array = Object.entries(input_array.reduce((acc, curr) => {
return {
...acc,
[curr.day]: curr.day in acc ? [...acc[curr.day], curr] : [curr]
}
}, {})).map(([key, value]) => ({
name: value[0].name,
day: key,
schedule: value.map(val => ({
time: val.time,
task: val.task
}))
}))
console.log(result_array)

const data = [{"name":"alagu","day":"monday","time":"morning","task":"studying"},{"name":"alagu","day":"monday","time":"evening","task":"playing"},{"name":"alagu","day":"monday","time":"night","task":"sleeping"},{"name":"alagu","day":"sunday","time":"morning","task":"playing"},{"name":"alagu","day":"sunday","time":"evening","task":"playing"},{"name":"alagu","day":"sunday","time":"night","task":"sleeping"}]
let t, r = [...new Set(data.map(i=>i.day))]
.map(day=>(t=data.filter(i=>i.day===day),
{name: t[0].name, day, schedule: t.map(({name, day, ...o})=>o)}))
console.log(r)

I would personally introduce a general purpose groupBy() helper, that allows you to group a collection based on a key.
function groupBy(iterable, fn) {
const groups = new Map();
for (const item of iterable) {
const key = fn(item);
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(item);
}
return groups;
}
With this helper defined we group the data using:
const groups = groupBy(input_array, item => JSON.stringify([item.name, item.day]));
The reason I use JSON.stringify() is because two arrays (objects) are only only equal to each other if they reference the same array. Therefore [item.name, item.day] will never match an existing key, since we just created the array instance. If we serialize the array (using JSON) we can compare 2 strings instead. Which are equal if they contain the same content.
// normal array comparison
["alagu", "monday"] === ["alagu", "monday"] //=> false
// serialized (using JSON) array comparison
'["alagu","monday"]' === '["alagu","monday"]' //=> true
After we've grouped the data, the groups structure looks like this:
// using object notation to display Map instance contents
Map{
'["alagu","monday"]': [
{ name: "alagu", day: "monday", time: "morning", task: "studying" },
{ name: "alagu", day: "monday", time: "evening", task: "playing" },
{ name: "alagu", day: "monday", time: "night" , task: "sleeping" },
],
'["alagu","sunday"]': [
{ name: "alagu", day: "sunday", time: "morning", task: "playing" },
{ name: "alagu", day: "sunday", time: "evening", task: "playing" },
{ name: "alagu", day: "sunday", time: "night" , task: "sleeping" },
],
}
We can then convert this into an array using Array.from(groups) and map() over the key/value pairs to transform them into the desired output.
const result_array = Array.from(groups).map(([json, items]) => {
const [name, day] = JSON.parse(json);
const schedule = items.map(({ time, task }) => ({ time, task }));
return { name, day, schedule };
});
const input_array = [
{ name: "alagu", day: "monday", time: "morning", task: "studying" },
{ name: "alagu", day: "monday", time: "evening", task: "playing" },
{ name: "alagu", day: "monday", time: "night" , task: "sleeping" },
{ name: "alagu", day: "sunday", time: "morning", task: "playing" },
{ name: "alagu", day: "sunday", time: "evening", task: "playing" },
{ name: "alagu", day: "sunday", time: "night" , task: "sleeping" },
];
const groups = groupBy(input_array, item => JSON.stringify([item.name, item.day]));
const result_array = Array.from(groups).map(([json, items]) => {
const [name, day] = JSON.parse(json);
const schedule = items.map(({ time, task }) => ({ time, task }));
return { name, day, schedule };
});
console.log(result_array);
// groupBy() helper
function groupBy(iterable, fn) {
const groups = new Map();
for (const item of iterable) {
const key = fn(item);
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(item);
}
return groups;
}
In the above code we turn the serialized key back into a JavaScript structure using JSON.parse(), this allows us to grab the name and day of the current group.
We then need to transform items—an array of objects that still contain all the properties—into an array of objects that only have the time and task property.
.map(({ time, task }) => ({ time, task })) does exactly that. It is a combination of object destructuring and the property definition shorthand.

Related

Split Array of Objects using a key

I have a data array like below which needs to be a structured by using Value property with Start and End Time
[{
"Timestamp": "2021-09-30T21:38:46.7000122Z",
"Value": "496",
},
{
"Timestamp": "2021-10-01T01:08:47.4690093Z",
"Value": "496",
},
{
"Timestamp": "2021-10-02T15:38:02.5080108Z",
"Value": "207",
},
{
"Timestamp": "2021-10-02T16:30:32.3410034Z",
"Value": "207",
},
{
"Timestamp": "2021-10-02T21:45:32.7460021Z",
"Value": "207",
},
{
"Timestamp": "2021-10-02T22:38:02.5839996Z",
"Value": "413",
},
{
"Timestamp": "2021-10-02T23:30:33.3980102Z",
"Value": "413",
},
{
"Timestamp": "2021-10-03T00:23:02.7130126Z",
"Value": "413",
},
{
"Timestamp": "2021-10-03T11:47:47.8630065Z",
"Value": "413",
}]
Is there a way to compose the above array to into below format like group using Value and pick the the 1st object timestamp as Start Time and last object timestamp value as End Time like below
[{
"id": 496
"stTime": "2021-09-30T21:38:46.7000122Z"
"endTime": "2021-10-01T01:08:47.4690093Z"
},{
"id": 207
"stTime": "2021-10-02T15:38:02.5080108Z"
"endTime": "2021-10-02T21:45:32.7460021Z"
},{
"id": 413
"stTime": "2021-10-02T22:38:02.5839996Z"
"endTime": "2021-10-03T11:47:47.8630065Z"
}]
const data = [
{
Timestamp: "2021-09-30T21:38:46.7000122Z",
Value: "496",
},
{
Timestamp: "2021-10-01T01:08:47.4690093Z",
Value: "496",
},
{
Timestamp: "2021-10-02T15:38:02.5080108Z",
Value: "207",
},
{
Timestamp: "2021-10-02T16:30:32.3410034Z",
Value: "207",
},
{
Timestamp: "2021-10-02T21:45:32.7460021Z",
Value: "207",
},
{
Timestamp: "2021-10-02T22:38:02.5839996Z",
Value: "413",
},
{
Timestamp: "2021-10-02T23:30:33.3980102Z",
Value: "413",
},
{
Timestamp: "2021-10-03T00:23:02.7130126Z",
Value: "413",
},
{
Timestamp: "2021-10-03T11:47:47.8630065Z",
Value: "413",
},
];
function processTimestamps(timestamps) {
return timestamps.reduce((retval, { Timestamp, Value }) => {
const currTime = new Date(Timestamp)
const existing = retval.find(obj => obj.id === Value)
if(existing){
const startTime = new Date(existing.stTime)
const endTime = new Date(existing.endTime)
if (currTime < startTime){
existing.startTime = Timestamp
}
if (currTime > endTime){
existing.endTime = Timestamp
}
}else{
retval.push({
id: Value,
stTime: Timestamp,
endTime: Timestamp
})
}
return retval
}, []);
}
console.log(processTimestamps(data));
You can use Object.values() to extract teh values result array of Array.prototype.reduce()ing the data
Code:
const data = [{Timestamp: '2021-09-30T21:38:46.7000122Z',Value: '496',},{Timestamp: '2021-10-01T01:08:47.4690093Z',Value: '496',},{Timestamp: '2021-10-02T15:38:02.5080108Z',Value: '207',},{Timestamp: '2021-10-02T16:30:32.3410034Z',Value: '207',},{Timestamp: '2021-10-02T21:45:32.7460021Z',Value: '207',},{Timestamp: '2021-10-02T22:38:02.5839996Z',Value: '413',},{Timestamp: '2021-10-02T23:30:33.3980102Z',Value: '413',},{Timestamp: '2021-10-03T00:23:02.7130126Z',Value: '413',},{Timestamp: '2021-10-03T11:47:47.8630065Z',Value: '413'}]
const result = Object
.values(
data.reduce((a, { Value, Timestamp }) => {
a[Value] = a[Value] || {
id: +Value,
stTime: Timestamp,
}
a[Value].endTime = Timestamp
return a
}, {})
)
console.log(result)
const data = [{Timestamp: '2021-09-30T21:38:46.7000122Z',Value: '496',},{Timestamp: '2021-10-01T01:08:47.4690093Z',Value: '496',},{Timestamp: '2021-10-02T15:38:02.5080108Z',Value: '207',},{Timestamp: '2021-10-02T16:30:32.3410034Z',Value: '207',},{Timestamp: '2021-10-02T21:45:32.7460021Z',Value: '207',},{Timestamp: '2021-10-02T22:38:02.5839996Z',Value: '413',},{Timestamp: '2021-10-02T23:30:33.3980102Z',Value: '413',},{Timestamp: '2021-10-03T00:23:02.7130126Z',Value: '413',},{Timestamp: '2021-10-03T11:47:47.8630065Z',Value: '413'}]
var res = data.map(e=>e.Value).filter((e,i,a)=>a.indexOf(e)==i).map(e=>({id:e,times:time.filter(x=>x.Value==e).map(x=>x.Timestamp)}))
.map(e=>({t:e,s:new Date(e)})).sort((a,b)=>a.s-b.s > 1).map(e=>e.t)
.map(e=>({id:e.id,stTime:e.times.shift(),endTime:e.times.pop()}))
console.log(res);

Combine Object base on object property in array on objects

I just want to merge the objects on the base of one of the properties also want to add missing Days name in the output.
Take this for an example:
var array = [
{
"heure1": "14:00",
"heure2": "17:00",
"day": "Sunday",
},
{
"heure1": "08:00",
"heure2": "13:00",
"day": "Sunday",
},
{
"heure1": "14:00",
"heure2": "16:00",
"day": "Monday",
},
{
"heure1": "08:00",
"heure2": "18:00",
"day": "Monday",
},
];
Expected result:
var array = [
{
"heure": ["14:00","17:00","08:00","13:00"],
"day": "Sunday",
},
{
"heure": ["14:00","16:00","08:00","18:00"],
"day": "Monday",
},
{
"heure": [],
"day": "Saturday",
},
{
"heure": [],
"day": "Friday",
},
{
"heure": [],
"day": "Thursday",
},
{
"heure": [],
"day": "Wednesday",
},
{
"heure": [],
"day": "Tuesday",
},
];
Im also trying some of stack overflow answers but Not getting success :-(
Order of the day dose not matter.
Thanks in advance.
My try
<script>
var array = [{
"heure1": "14:00",
"heure2": "17:00",
"DAY": "Sunday",
},
{
"heure1": "08:00",
"heure2": "13:00",
"DAY": "Sunday",
},
{
"heure1": "14:00",
"heure2": "16:00",
"DAY": "Monday",
},
{
"heure1": "08:00",
"heure2": "18:00",
"DAY": "Monday",
},
];
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sunday", "Saturday"];
var result = [];
days.map(function (day) {
var daysInArray = array.filter(function (a) {
return day == a.DAY
})
// console.log(daysInArray);
if (daysInArray.length) {
time = [];
daysInArray.map(function (item, i) {
for (var key in item) {
if (daysInArray[0].hasOwnProperty(key) && key != "DAY") {
time.push(item[key])
}
}
})
result.push({
"day": day,
"heure": time
})
} else {
result.push({
"day": day,
"heure": []
})
}
})
console.log(result);
</script>
You could first create the 7 entries for the 7 days of the week, each with an empty array for the heure property.
Then iterate the original data, look up the right entry, and push the two times to the heure array.
Note that your Day property has different spellings in your example input (DAY, Day). I would strongly suggest to use all lowercase for such property names.
Here is an implementation:
var array = [{"heure1": "14:00","heure2": "17:00","day": "Sunday",}, {"heure1": "08:00","heure2": "13:00","day": "Sunday",}, {"heure1": "14:00","heure2": "16:00","day": "Monday",}, {"heure1": "08:00","heure2": "18:00","day": "Monday", },];
let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
let obj = Object.fromEntries(days.map(day => [day, { heure: [], day }]));
for (let {heure1, heure2, day} of array) obj[day].heure.push(heure1, heure2);
let result = Object.values(obj);
console.log(result);
my way...
var arr_1 =
[ { heure1: '14:00', heure2: '17:00', day: 'Sunday' }
, { heure1: '08:00', heure2: '13:00', day: 'Sunday' }
, { heure1: '14:00', heure2: '16:00', day: 'Monday' }
, { heure1: '08:00', heure2: '18:00', day: 'Monday' }
]
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
const res = days.map(d=>
{
let r = { heure:[], day:d }
arr_1.filter(x=>x.day===d)
.forEach(({heure1,heure2})=> { r.heure.push(heure1,heure2) })
r.heure.sort()
return r
})
console.log( res )
.as-console-wrapper { max-height: 100% !important; top: 0; }
Is that result structure necessary?
If not, modifying the result structure, you could do something like this:
const getHeureByDay = (heureArray) => {
let result = {
Sunday: { heure: [] },
Monday: { heure: [] },
Tuesday: { heure: [] },
Wednesday: { heure: [] },
Thursday: { heure: [] },
Friday: { heure: [] },
Saturday: { heure: [] },
};
heureArray.forEach((heureItem) => {
Object.keys(heureItem).forEach((key) => {
if (key !== "day") {
result[heureItem.day].heure.push(heureItem[key]);
}
})
});
return result;
};
const heureArray = [
{
"heure1": "14:00",
"heure2": "17:00",
"day": "Sunday",
},
{
"heure1": "08:00",
"heure2": "13:00",
"day": "Sunday",
},
{
"heure1": "14:00",
"heure2": "16:00",
"day": "Monday",
},
{
"heure1": "08:00",
"heure2": "18:00",
"day": "Monday",
}
];
console.log(getHeureByDay(heureArray));

How to generate different ObjectId's with MongoDB's positional operator $[]?

I want to update every element in the array days (I got 7 days, here I only show 3) with the MongoDB positional operator $[]. The update correctly pushes an object into every single element of the array meals. However, their Object Id's are the same, and I would like them to be different since I will be mapping them. Any ideas?
"_id": {
"$oid": "5db749cf657e1b1e0c3d241c"
},
"finished": false,
"days": [
{
"dayName": "Monday",
"meals": [
{
"_id": {
"$oid": "5dba1cde12f2b650e4b4f89d"
},
"mealName": "Breakfast",
"recipes": []
}
]
},
{
"dayName": "Tuesday",
"meals": [
{
"_id": {
"$oid": "5dba1cde12f2b650e4b4f89d"
},
"mealName": "Breakfast",
"recipes": []
}
]
},
{
"dayName": "Wednesday",
"meals": [
{
"_id": {
"$oid": "5dba1cde12f2b650e4b4f89d"
},
"mealName": "Breakfast",
"recipes": []
}
],
}
]
}

Merge complex multidimensionnal array

In Javascript, I created a multidimensionnal array, but for another purpose, I need to convert it.
So my array is like this
array [
0 => {
"ulStatic": [
0 => {
"day": "2019-03-30 18:30:00"
"id": "7"
"origin": "intentions"
}
]
"ulDynamic": [
0 => {
"day": "2019-03-30 18:30:00"
"id": "275"
"origin": "obs"
}
]
"ulCreatedDynamic": []
}
1 => {
"ulStatic": [
0 => {
"day": "2019-03-31 09:30:00"
"id": "8"
"origin": "intentions"
}
]
"ulDynamic": []
"ulCreatedDynamic": []
}
2 => {
"ulStatic": []
"ulDynamic": []
"ulCreatedDynamic": [
0 => {
"day": "2019-04-03 19:30:00"
"id": "277"
"origin": "obs"
}
]
}
]
And I'm trying to have this array :
array [
0 => {
"day": "2019-03-30 18:30:00"
"elements": [
0 => {
"id": "7"
"origin": "intentions"
}
1 => {
"id": "275"
"origin": "obs"
}
]
}
1 => {
"day": "2019-03-31 09:30:00"
"elements": [
0 => {
"id": "8"
"origin": "intentions"
}
]
}
2 => {
"day": "2019-04-03 19:30:00"
"elements": [
0 => {
"id": "277"
"origin": "obs"
}
]
}
]
And I must admit that I do not know where to start. I'm looking for map(), splice(), concat(), but it's confusing for me.
Can you help me to give some advices to achieve that ?
Thank you
You could group your data by day by iterating the values of the value of the objects and their array.
var array = [{ ulStatic: [{ day: "2019-03-30 18:30:00", id: "7", origin: "intentions" }], ulDynamic: [{ day: "2019-03-30 18:30:00", id: "275", origin: "obs" }], ulCreatedDynamic: [] }, { ulStatic: [{ day: "2019-03-31 09:30:00", id: "8", origin: "intentions" }], ulDynamic: [], ulCreatedDynamic: [] }, { ulStatic: [], ulDynamic: [], ulCreatedDynamic: [{ day: "2019-04-03 19:30:00", id: "277", origin: "obs" }] }],
result = array.reduce((r, o) => {
Object
.values(o)
.forEach(a => a.forEach(({ day, id, origin }) => {
var temp = r.find(p => day === p.day);
if (!temp) r.push(temp = { day, elements: [] });
temp.elements.push({ id, origin });
}));
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
let originalArr = [{
ulStatic: [
{
day: '2019-03-30 18:30:00',
id: '7',
origin: 'intentions'
}
],
ulDynamic: [
{
day: '2019-03-30 18:30:00',
id: '275',
origin: 'obs'
}
],
ulCreatedDynamic: []},{ulStatic: [
{
day: '2019-03-31 09:30:00',
id: '8',
origin: 'intentions'
}
],
ulDynamic: [],
ulCreatedDynamic: []},{ ulStatic: [],
ulDynamic: [],
ulCreatedDynamic: [
{
day: '2019-04-03 19:30:00',
id: '277',
origin: 'obs'
}
]}];
let op = originalArr.map(item => {
let ulStatic = item.ulStatic.map(ul => {
return {
id: ul.id,
origin: ul.origin
};
});
let ulDynamic = item.ulDynamic.map(ul => {
return {
id: ul.id,
origin: ul.origin
};
});
let ulCreatedDynamic = item.ulCreatedDynamic.map(ul => {
return {
id: ul.id,
origin: ul.origin
};
});
let day;
if (ulStatic.length > 0) {
day = item.ulStatic[0].day;
} else if (ulDynamic.length > 0) {
day = item.ulDynamic[0].day;
} else if (ulCreatedDynamic.length > 0) {
day = item.ulCreatedDynamic[0].day;
}
return {
day: day,
elements: [].concat(ulStatic).concat(ulDynamic)
};
});
console.log(op);
Check this out
grouping the input by day with reduce and return the object values.
const inputAry = [{
"ulStatic": [{
"day": "2019-03-30 18:30:00",
"id": "7",
"origin": "intentions"
}],
"ulDynamic": [{
"day": "2019-03-30 18:30:00",
"id": "275",
"origin": "obs"
}],
"ulCreatedDynamic": []
},
{
"ulStatic": [{
"day": "2019-03-31 09:30:00",
"id": "8",
"origin": "intentions",
}],
"ulDynamic": [],
"ulCreatedDynamic": []
},
{
"ulStatic": [],
"ulDynamic": [],
"ulCreatedDynamic": [{
"day": "2019-04-03 19:30:00",
"id": "277",
"origin": "obs"
}]
}
];
const groupByDay = inputAry.reduce((group, statics) => {
// flattens the statics array
[].concat.apply([], Object.values(statics))
.forEach(({
day,
id,
origin
}) => {
// creates a dictionary entry with day as key, if already exist use the existing one or creates a new entry
group[day] = group[day] || {
day,
elements: []
};
// push the id and origin to elements
group[day].elements.push({
id,
origin
});
});
return group;
}, {});
const expectedResult = Object.values(groupByDay);
console.log(expectedResult);

how to remove two json objects with same id

If I have a .json file with the following contents:
[
{
"id": "1234",
"day": "Monday",
"course": "Math110",
},
{
"id": "1234",
"day": "Wednesday",
"title": "Math110",
},
{
"id": "1345",
"day": "Tuesday",
"title": "Economics210",
}
]
How can I remove all the objects with id "1234" in Javascript? (note there are two objects with the same ID)
Would delete["1234"] work?
Use .filter to filter out elements of an array:
const input = [{
"id": "1234",
"day": "Monday",
"course": "Math110",
},
{
"id": "1234",
"day": "Wednesday",
"title": "Math110",
},
{
"id": "1345",
"day": "Tuesday",
"title": "Economics210",
}
];
const output = input.filter(({ id }) => id !== '1234');
console.log(output);
You cannot use delete operator because its for deleting a property in an object. You actually want to delete an object inside an array.
Use the good old for loop and Array.splice():
var inputArray = [{
"id": "1234",
"day": "Monday",
"course": "Math110",
},
{
"id": "1234",
"day": "Wednesday",
"title": "Math110",
},
{
"id": "1345",
"day": "Tuesday",
"title": "Economics210",
}
];
var deleteId = "1234";
for (var i = 0; i < inputArray.length; i++) {
if (inputArray[i].id === deleteId) {
inputArray.splice(i, 1);
i = i-1;
}
}
console.log(inputArray);
Note: If you are fine with creating another array and not modifying the existing array, use Array.filter() as mentioned in the other answers.
You can parse the JSON to an array and then use Array.prototype.filter to get a new array which doesn't have the objects with id "1234":
const json = '[{"id":"1234","day":"Monday","course":"Math110"},{"id":"1234","day":"Wednesday","title":"Math110"},{"id":"1345","day":"Tuesday","title":"Economics210"}]';
const result = JSON.parse( json ).filter( obj => obj.id !== "1234" );
console.log( JSON.stringify( result, null, ' '.repeat(8) ) );
You have to delete by specifying the position of the item in the array:
const arr = [{
"id": "1234",
"day": "Monday",
"course": "Math110",
},
{
"id": "1234",
"day": "Wednesday",
"title": "Math110",
},
{
"id": "1345",
"day": "Tuesday",
"title": "Economics210",
}
];
arr.forEach(function(item, i){
if(item.id == "1234")
delete arr[i];
});
console.log(arr.filter(j => j))
You can use filter method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
items = [
{
"id": "1234",
"day": "Monday",
"course": "Math110",
},
{
"id": "1234",
"day": "Wednesday",
"title": "Math110",
},
{
"id": "1345",
"day": "Tuesday",
"title": "Economics210",
}
];
items.filter(function(item) {
return item.id !== '1234';
});

Categories

Resources