iteration on Datasource in Angular - javascript

I want to make a function which iterates through an array of object and set the property status to false.
The array of obj is a datasource on angular table.
this.lightService.getLamp()
.subscribe(
(response) => {
this.lampData = response;
this.dataSource.data = response;
},
(error) => {
console.log('error ' + error);
}
The Data source
{
"id": 1,
"group" : 1,
"name": "Lamp 1",
"connected": " Not Connected",
"status": true,
"address": "1",
"channel": "All",
"temperature": 3200,
"error": false,
"errorMessage": "Not Working at this moment"
},
{
"id": 2,
"group" : 2,
"name": "Lamp 2",
"connected": "Connected",
"status": true,
"address": "2",
"channel": "All",
"temperature": 6500,
"error": false,
"errorMessage": "Not Working at this moment"
},
{
.....
}
]

You can use the .map operator for iterating through all the objects in an array. I suppose the below code should work for you.
this.lightService.getLamp()
.subscribe(
(response) => {
this.lampData = response;
this.dataSource.data = response;
this.dataSource.data.map(item => {
item.status = false
})
},
(error) => {
console.log('error ' + error);
}

Related

Issue while updating nested data createEntityAdapter RTK query

I am working on the chat that is utilising RTK Query with entity adapters. We created nested normalised createEntityAdapter . I want to update the message key from onCacheEntryAdded, but not able to update nested object. I'm attaching the query endpoint code along with sample response.
RTK Query Endpoint
endpoints: builder => ({
getMessages: builder.query({
query: ({ orderId, userId, channel }) => {
return {
url: `/messages?orderId=${orderId}&userId=${userId}`,
method: 'GET',
}
},
transformResponse(response, meta, arg) {
return messagesAdapter.setAll(messagesAdapter.getInitialState(), [
{
id: `${arg.orderId}-${arg.userId}`,
isTyping: false,
channel: arg.channel,
orderId: arg.orderId,
messages: messagesAdapter.addMany(
messagesAdapter.getInitialState(),
response,
),
},
])
},
async onCacheEntryAdded(
arg,
{ updateCachedData, cacheDataLoaded, cacheEntryRemoved, cacheData },
) {
try {
await cacheDataLoaded
updateCachedData(draft => {
messagesAdapter.updateOne(draft, {
id: '62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72',
changes: {
messages: messagesAdapter.updateOne(
messagesAdapter.getInitialState(),
{
id: '62da7221bc0eb3a259fc2256',
changes: {
message: 'updated message',
},
},
),
},
})
})
} catch {
// no-op in case `cacheEntryRemoved` resolves before `cacheDataLoaded`,
// in which case `cacheDataLoaded` will throw
}
await cacheEntryRemoved
},
providesTags: (result, error, arg) => {
console.log('providesTags', result, error, arg)
return ['chat']
},
}),
}),
Sample response
{
"ids": [
"62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72"
],
"entities": {
"62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72": {
"id": "62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72",
"isTyping": false,
"channel": "62d7d9266599a9f0c3bcdaba",
"orderId": "62d529f60be7549be1f53df3",
"messages": {
"ids": [
"62da7221bc0eb3a259fc2256",
"62da724dbc0eb3a259fc2260",
"62da75559f7a23f89a0958d4",
"62da94e59f7a23f89a0958ed"
],
"entities": {
"62da7221bc0eb3a259fc2256": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "dsds",
"sentAt": "2022-07-22T09:47:13.000Z",
"id": "62da7221bc0eb3a259fc2256"
},
"62da724dbc0eb3a259fc2260": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "hello nm",
"sentAt": "2022-07-22T09:47:57.000Z",
"id": "62da724dbc0eb3a259fc2260"
},
"62da75559f7a23f89a0958d4": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "b",
"sentAt": "2022-07-22T10:00:53.000Z",
"id": "62da75559f7a23f89a0958d4"
},
"62da94e59f7a23f89a0958ed": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "hello there",
"sentAt": "2022-07-22T12:15:31.000Z",
"id": "62da94e59f7a23f89a0958ed"
}
}
}
}
}
}

React Native - json - [Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'key.time.date')]

I am writing a React Native app which fetchs data from server. I need to receive json and return only some received objects (the ones with date later than the current one). The problem occurs midway.
Here is my code
import {serverURL} from '../assets/config/server'
export const getEventsByRegion = (region) => {
let events;
let url = `${serverURL}events/eventList`
return fetch(url, {
method: 'GET',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json();})
.then(responseData => {
events = responseData;
})
.catch(err => {
console.log("fetch error" + err);
})
.then( () =>
{
if(events){
events = Object.values(events).filter((key) => {
console.log(key)
return ((key.region[0] === region) )
})
} else
events = null;
if(events){
events = Object.values(events).filter((key) => {
console.log(key.name, key.time)
console.log(key.time.date)
return (toSimpleDate(new Date(key.time.date)) >= toSimpleDate(new Date()))
})
}
if(events !== undefined) {
return events;
}
}
);
}
toSimpleDate = (date) => {
return date.setHours(0,0,0,0);
}
And here is my console.log() output
//first output - full
//1
Object {
"__v": 0,
"_id": "607e06dd5195440015e95ed6",
"description": "",
"geoLocation": Object {
"_id": "607e06dd5195440015e95ed7",
"geometry": Object {
"coordinates": Array [
null,
null,
],
"type": "Point",
},
"type": "Feature",
},
"inBus": true,
"name": "Test event 1",
"region": Array [
"Region1",
],
"time": Object {
"date": "2021-04-19T22:37:37.055Z",
"timeFrom": "2021-04-19T22:37:37.055Z",
"timeTo": "2021-04-20T10:37:00.000Z",
},
}
//2
Object {
"__v": 0,
"_id": "60911a388446fe0015c8f7e0",
"description": "test description",
"geoLocation": Object {
"_id": "60911a388446fe0015c8f7e1",
"geometry": Object {
"coordinates": Array [
null,
null,
],
"type": "Point",
},
"type": "Feature",
},
"inBus": false,
"name": "Test event 2",
"region": Array [
"Region1",
],
"time": Object {
"date": "2021-05-26T09:54:00.000Z",
"timeFrom": "2021-05-04T08:00:15.410Z",
"timeTo": "2021-05-04T12:25:15.410Z",
},
}
//second output - a part only
//1
Test event 1 Object {
"date": "2021-01-01T12:41:00.000Z",
"timeFrom": "2020-12-27T11:41:48.610Z",
"timeTo": "2020-12-27T12:41:48.610Z",
}
2021-01-01T12:41:00.000Z
//2
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'key.time.date')]
//
As you can see, it refuses to read key.time.date field (the example doesn't show it, but there is no problem with key.time nor with key.name). The origin of data is the same and I can't find the problem with structure.
Please help

How do I split nested objects into its separate objects in es6

My json data currently looks like this:
[
{
"timestamp": 345345,
"status": {
"code": 200,
"success": true,
"message": "Success",
"errors": []
},
"size": 1,
"nameList": [
{
"id": 74997
"status": "pending"
}
]
},
{
"timestamp": 45,
"status": {
"code": 200,
"success": true,
"message": "OK",
"errors": []
},
"size": 5,
"content": [
{
"id": 1260087,
"pilot": "Jujuki",
"nameId": 4343,
"RefId": "3453454"
}
]
}
]
How do I split up this object into 2 different object/arrays of data. I want everything with index 0 to go into the first new object, and everything with index 1 to go into the second new object.
What would be best es6 syntax method to use.
you can do Destructuring assignment, like the following:
const data = [{
timestamp: 345345,
status: {
code: 200,
success: true,
message: "Success",
errors: []
},
size: 1,
nameList: [{
id: 74997,
status: "pending"
}]
},
{
timestamp: 45,
status: {
code: 200,
success: true,
message: "OK",
errors: []
},
size: 5,
content: [{
id: 1260087,
pilot: "Jujuki",
nameId: 4343,
RefId: "3453454"
}]
}
];
const [firstObj, secondObj] = data;
console.log("the first Object: ", firstObj);
console.log("the second Object: ", secondObj);

How To $pull From Deeply Nested Document (mongoose)

I need to delete a location object from the locations array. It is deeply nested. I followed mongoose documentation but my attempts didn't work:
lists = [{
"listName": "Test",
"_id": "8d55f0afe545a0178c320706",
"listId": "5fd9a3bef6c39b2f9c4df65b",
"date": "12/15/2020",
"dueDate": "2020-11-18",
"items": [
{
"itemNumber": 123,
"description": "item123",
"onHand": 60,
"_id": "13dd1f26ecd2baeb61b3b455",
"locations": [
{
"locationName": "loc1",
"count": 10,
"_id": "50a2c969465ba8010bd48977"
},
{
"locationName": "loc2",
"count": 20,
"_id": "51c2f1d25311dc8fabdbf604a59b"
},
{
"locationName": "Loc3",
"count": 30,
"_id": "7cb0c1f51a91c384846d65f8b2ae"
}
]
},
{more lists}
Attempt:
router.post("/lists/deleteLoc", (req, res) => {
const {
listId,
list_id,
item_id,
location_id
} = req.body;
List.updateOne({
"lists.listId": listId,
"lists._id": list_id
}, {
$pull: {
"lists.$.items": {
locations: {
$elemMatch: {
_id: location_id
})
.then(() => res.json({
msg: "location removed"
}))
.catch((err) => res.status(400).json({
msg: "Error: " + err
}));
});
If the request location_id was "7cb0c1f51a91c384846d65f8b2ae" it should delete the last location from the array. The desired result:
lists = [{
"listName": "Test",
"_id": "8d55f0afe545a0178c320706",
"listId": "5fd9a3bef6c39b2f9c4df65b",
"date": "12/15/2020",
"dueDate": "2020-11-18",
"items": [
{
"itemNumber": 123,
"description": "item123",
"onHand": 60,
"_id": "13dd1f26ecd2baeb61b3b455",
"locations": [
{
"locationName": "loc1",
"count": 10,
"_id": "50a2c969465ba8010bd48977"
},
{
"locationName": "loc2",
"count": 20,
"_id": "51c2f1d25311dc8fabdbf604a59b"
}
]
},
{more lists}
I've tried basically all variations of this, but none have worked.
I'm also not sure if making a router.post or an axios.post request for deletion is correct. Should this be axios.delete and router.delete?
I've tried this in one of my similar DB and worked!
List.updateOne({ "listId": yourListId },
{
'$pull': {
'items.$[item].locations': { "_id": yourLocationId }
}
}, {
"arrayFilters": [
{
"item._id": yourItemId
}
]
}, function (err) {
if (err) {
res.json(err)
} else {
res.json({ message: "Updated" })
}
})
}
You've to put the values that're inside your DB from the object that you want to delete.
So if you want to delete the object with
"locationname" : "Loc3"
You should use
var yourListId = "5fd9a3bef6c39b2f9c4df65b";
var yourItemId = "13dd1f26ecd2baeb61b3b455";
var yourLocationId = "7cb0c1f51a91c384846d65f8b2ae";
Try it out!

.forEach(...) is undefined while fetching

I want to print every object of a JSON object by using the fetch API and iterate the response with a forEach method
function
artistSelected(evt){
let artistId = evt.target.parentElement.id;
fetch("http://localhost:3000/artists/"+artistId+"/albums")
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('a problem occured');
}
})
.then((response) => {
let albums = response;
albums.forEach(value => {
console.log(value)
})
.catch((error) => {
console.log(error);
})
})
}
when I run the function, I have the error TypeError: albums.forEach(...) is undefined and I cannot print every objects
an example of the Album JSON response could be:
[
{
"id": "the_rolling_stones",
"artistId": "rolling_stones",
"year": 1964,
"title": "The Rolling Stones",
"label": "ABKCO Records",
"cover": "http://cps-static.rovicorp.com/3/JPG_500/MI0002/193/MI0002193977.jpg"
},
{
"id": "12_5",
"year": 1964,
"artistId": "rolling_stones",
"title": "12x5",
"label": "ABKCO Records",
"cover": "http://cps-static.rovicorp.com/3/JPG_500/MI0000/498/MI0000498502.jpg"
},
{
"id": "out_of_our_heads",
"artistId": "rolling_stones",
"year": 1965,
"title": "Out of Our Heads",
"label": "ABKCO Records",
"cover": "http://cps-static.rovicorp.com/3/JPG_500/MI0001/682/MI0001682084.jpg"
}
]
and when I print the response of the first '.then' I have:
Res
ponse { type: "cors", url: "http://localhost:3000/artists/the_clash/albums", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false }
Assuming it's a typesafety issue, the solution is as follows:
.then((response) => {
if (response) {
let albums = response.json();
albums.forEach(value => {
console.log(value)
})
} else {
throw new Error('a problem occured');
}
}).catch((error) => {
console.log(error);
})
I found the solution,
I don't know why nobody saw it but the catch wasn't in the right place, because when I switch to Chrome, the error is not from the foreach but from the catch.
For a reference, I am taking your JSON response(Array of objects) and by that, we can easily iterate the array by foreach loop
var album =[
{
"id": "the_rolling_stones",
"artistId": "rolling_stones",
"year": 1964,
"title": "The Rolling Stones",
"label": "ABKCO Records",
"cover": "http://cps-static.rovicorp.com/3/JPG_500/MI0002/193/MI0002193977.jpg"
},
{
"id": "12_5",
"year": 1964,
"artistId": "rolling_stones",
"title": "12x5",
"label": "ABKCO Records",
"cover": "http://cps-static.rovicorp.com/3/JPG_500/MI0000/498/MI0000498502.jpg"
},
{
"id": "out_of_our_heads",
"artistId": "rolling_stones",
"year": 1965,
"title": "Out of Our Heads",
"label": "ABKCO Records",
"cover": "http://cps-static.rovicorp.com/3/JPG_500/MI0001/682/MI0001682084.jpg"
}
];
album.forEach(value =>{
console.log(value.title)
});

Categories

Resources