How to map new property values to an array of JSON objects? - arrays

I'm reading back record sets in an express server using the node mssql package. Reading back the values outputs an array of Json objects as expected.
Now I need to modify the Email propoerty value of each Json object. So I tried looping through the recordset and changing the value at each index:
var request = new sql.Request(sql.globalConnection);
request.input('p_email', sql.VarChar(50), userEmail);
request.execute('GetDDMUserProfile', function(err, recordsets, returnValue) {
for (var i = 0; i < recordsets.length; i++){
recordsets[i].Email = "joe#gmail.com";
}
console.log(recordsets);
});
But instead of modifying the Emailvalue of each Json object, this code just appends a new email property to the last Json object.
How can you map new property values to an array of JSON objects?
Example output:
An example of the output is shown below, where a new Email property has been added to the end of the array instead of changing each existing property value:
[
[
{
ID:[
4
],
UserName:"Brian",
Email:"joe#gmail.com"
},
{
ID:[
5
],
UserName:"Brian",
Email:"joe#gmail.com"
}
Email:'joe#gmail.com' ]
]

The issue here is that your dataset appears to not be an array of JSON objects but, rather, an array of arrays of JSON objects. If you know for certain that you'll always have only one array in the top-most array, then you can solve the problem like this:
recordsets[0][i].Email = "joe#gmail.com";
to always target the first array in the top-most array. However, if the top-most array could potentially have more than one array, that'll be a different kind of issue to solve.

Related

de-duping items in a mongoose list of populate IDs

I have a mongoose object which contains an array of ObjectIds, being used for population from another table. I want to be able to dedupe these. eg I have
[ '61e34f3293d9361bbb5883c7' ,'61e34f3293d9361bbb5883c7', '61e34f3293d9361bbb5883c7' ]
When i print and iterate through these they look like strings.
But they also have an _id property, so I think they're somehow "populated" or at least contain references to the child table.
What's the best way to do this? I tried:
const uniqueTokens = _.uniqBy(tokens, '_id') which doesn't seem to work as _id is some kind of Object.
converting to a string will allow me to dedupe:
const tokens = this.tokens || []
let newTokens: string[] = []
for (let t of tokens) {
const text = t.toString()
// clog.info('t', t, t._id, typeof t._id)
if (!newTokens.includes(text)) {
newTokens.push(text)
}
}
but then these aren't real Objects I can assign back to the original parent object.
// this.tokens = newTokens
await this.save()
I could maybe go through and re-find the objects, but that seems to be digging deeper into the hole!
Seems there must be a better way to handle these type of types...
related searches
How to compare mongoDB ObjectIds & remove duplicates in an array of documents using node.js?
I also tried using lean() on the tokens array to try and convert it back to a simple list of references, in case somehow the 'population' could be undone to help.
I'm down to creating a unique signature field for the referenced items and de-duping based on that.

Best approach in moving data from one array to a new array in angular ts

.subscribe((dataChart) => {
// console.log(dataChart)
var forxaxis = []
var cd = [dataChart]
// console.log(cd)
cd.forEach(element => {
forxaxis.push(element.strRequestDate)
console.log(forxaxis)
});
},
Im trying to move my data in the first array into a new array so that I can use it with chart.js. but it didnt work.
dataChart contain 2 column of data. i insert dataChart into an array called cd. then i tried to push one of the column from dataChart which is called strRequestDate into a new array called forxaxis but it just didnt work as per expected. the result is as shown in the image attached.
this is how the data look like. it was called by using sharepoint API
error and the data
You can use array.map property here, so you don't need to push data manually from one array to another
I have taken sample data in dataChart array for demonstration purpose only.
let dataChart = [{strRequestId: 1, strRequestDate: 'ABC'}, {strRequestId: 1, strRequestDate: 'PQR'}];
let forxaxis = dataChart.map(x => x.strRequestDate);
console.log(forxaxis);
Demo
Output:

Access object properties React-Native

I have a response from the server that looks like this
[
{
"metric":{
"id":"b66178b8-dc18-11e8-9f8b-f2801f1b9fd1",
"name":"Detector de fum bucatarie",
"metricValueType":"DOUBLE",
"metricType":"DEVICE_VALUE",
"groupUUID":null,
"projectUUID":null,
"companyUUID":"ccab28ed-3dcf-411f-8748-ec7740ae559c",
"unit":null,
"formula":null
},
"data":{
"1550150771819":"10.310835857351371"
}
}
]
Data property contains a hashMap with Timestamp and a Value.
When I try to get any value I recive this error:
myErrorTypeError: undefined is not an object (evaluating 'metricValues.metric.id')
How can I access a property ? I tried both methods :
metricValues.metric.id
and
metricValues["metric"]["id"]
How can I get the hashMap values?
I already tried this :
const timestamp = Object.keys(metricValues.data)[0];
const values = Object.values(metricValues.data)[0];
Your data is an array of objects. So even though your data has only one object, still it is an array of objects.
your object is at index 0 of the array.
You can access the metric Id as follows,
metricValues[0].metric.id
Try This (put that [0])
metricValues[0].metric.id
Your response from the server is an array. And the metric object is in the first element of that array.
To access the id inside the metric object you need to pass the index at which that object is present in the array which is 0 here.
That's why use :
metricValues[0].metric.id

Storing an array in a Firebase Database

I am trying to store an array in the Firebase Database, but I'm not sure how to do it properly.
I am wanting to store an array such as:
var exampleArray = ["item1", "item2", "item3"]
The reason why is I populate a UIPicker with values from an array, and rather than having to push an update to the app each time to add a new value, it would be better if I could just update the database and instantly add the new value to each app.
Is there any way that I could store the values in the database and pull the values from the database and store it into an array as shown above?
Thank you.
The Firebase setValue method will accept an array just the same as a String or Integer. So you can read and write the values in the same way -
var ref: DatabaseReference!
ref = Database.database().reference()
var exampleArray = ["item1", "item2", "item3"]
// Write the array
ref.child("myArray").setValue(exampleArray)
// Read the array
ref.child("myArray").observe(.value) { snapshot in
for child in snapshot.children {
// Add the values to your picker array here
}
}
A simple solution would be read JSON from a Firebase Database Reference containing the array, and deserealize it in swift to a native swift array. See point 2 at https://firebase.google.com/docs/database/#implementation_path

Value from Object using node

The below is my data, its type is object, I am not able to get my data after stringifying and parsing too...how can I get message alone using nodejs.
[ { ID: '361',Message: 'customg' } ]
I guess what you want to say is this. You got an array of object(s) like this:
var myarray =[ { ID: '361',Message: 'customg' } ] ;
stringifying the json object using JSON.stringify(myarray), gives :
"[{\"ID\":\"361\",\"Message\":\"customg\"}]"
parsing back using JSON.parse ("[{\"ID\":\"361\",\"Message\":\"customg\"}]"), returns your original object.
Now to access the 'Message' member, you need to access the first item in the array, then the Message property of the object, like this:
var msg =myarray [0].Message ;
This code assumes, you got an object with a property Message as the first element of the array.
Your data is,
data = [ { ID: '361',Message: 'customg' } ]
data variable contains list of Objects(Here there is only one object in list).
var msg = data[0].Message // You will get message property
In your case you already have list of objects, so no need to stringify/parse the list.
JSON.stringify() : used when you want to convert your JSON object to string.
JSON.parse() : used when you want JSON object from string.(given that string contains proper JSON object)

Resources