I have an array of some data like this:
anonymous {
id: 1680,
data:
{ _ID: 0,
JOB_ID: 1333,
RecNum: 11832338,
Pressure: 999.439,
Pressure2: 714.131 },
creationDate: 2018-05-09T14:00:23.199Z,
job: 1 }
What I need to do is have each item that has pressure be put into its own array. So in this case I would end up with two arrays, Pressure and Pressure2, with those being the labels of each array
This code here only makes one array with double the values
Object.keys(this.query.rows).forEach(blob =>{
pipelines.data.push( this.query.rows[blob].data.Pressure)
pipelines.data.push( this.query.rows[blob].data.Pressure2)
pipelines.creationDate.push( this.query.rows[blob].creationDate)
})
I have also tried using the map function but in several attempts, I only get 'undefined' as a result.
I can get the keys of my data but how do I use this to test my data and put into the proper array?
const myDataKeys = Object.keys(this.query.rows[0].data);
Related
I have an array with this format:
var customerList = [{'email: ex#mail.com', 'name': 'John'}, {...}, {...}]
However I need to format a batch api call for the following format for each of the objects in the array:
api.post('/:batch_endpoint'), {
0: {url: '/:endpoint', data: {email: customerList[0].email}},
1: {...},
2: {...},
}
So essentially I'm wondering if there's a way to dynamically fill the records for the api call from that array or another list. So far I've tried to use Object.assign() but not sure if this is the right way forward:
var customerObject = Object.assign({}, customerList) outputs:
{
'0': {
email: 'ex#mail.com',
'...',
},
1: {...}
}
Beyond this point I'm not sure how I can format this api call properly.
Assuming that you're asking how to send batch updates as a 1st index-based array (instead of 0th index-based) you have at least a couple of options:
Option 1: Use the reduce method to add one to the key:
customerList.reduce((acc, data, idx) => ({
...acc,
[parseInt(idx) + 1]: {
url: "/:endpoint",
data
}
}), [])
Option 2: Use the unshift method to add a "garbage" value to the 0th index:
// Convert the values in the array into the shape you want to send
customerList.map(data => ({ url: "/:endpoint", data }))
// Insert garbage value at index 0
customerList.unshift(0)
Option 3: Update your API to support 0th indexed-arrays if you plan on sending data frequently. IMO, the above two solutions are a hack and less than ideal. However, this may not be possible in your situation.
I have an array of objects this.selection.selected which can have one or more values.
The below code is working fine if the array has only one value.
0: {hostName: "abc123"}
length: 1
console.log(this.selection.selected);
const dialogRef = this.dialog.open(saDialogComp, {
width: '600px'
data: {
hostName: this.selection.selected[0].hostName
}
});
How to make it work if the array has multiple objects as below?
0: {hostName: "abc123"}
1: {hostName: "abc456"}
length: 2
Because your this.selection.selected is an array, you can map a function over it to get all of the hostnames from the objects.
Depending on what your this.dialog.open needs to accept as the second parameter, you can try to modify your data to something like this:
const dialogRef = this.dialog.open(saDialogComp, {
width: '600px',
data: {
hostNames: this.selection.selected.map(a => a.hostName)
}
});
hostNames will now be an array of values from those objects, like:
[ 'abc123', 'abc456' ]
This will work with any amount of values in the array, be it one or 1000.
If you intend data.hostName to be a string, then you can:
// ...
data: {
hostName: this.selection.selected.map(o => o.hostName).join(', ')
}
This will:
convert the array of objects to an array of strings (only the value of the name);
join those strings into a single comma-separated string
I have a group of filters that is an Reactive Forms Object. I’ve taken the property values of the object and pushed it into an array.
// original filters object {claim_number: null, status: "Approved", patient: null, service_date: null}
let filterArr = []
Object.keys(this.filtersForm.value).forEach(filter => {
filterArr.push(this.filtersForm.value[filter])
// filterArr [null, “Approved, null, null]
})
I have a table that is comprised of an array of objects like the following:
"claims":[
{
"billed_amount":141.78,
"claim_number": "6596594-0",
"location":"University Hospital",
"member_id":"A1234567890",
"status":{
"label":"Approved",
"value": "Approved"
}
},
{
"billed_amount":341.70,
"claim_number": "2196524-3",
"location":"Springfield Hospital",
"member_id":"B1234567890",
"status":{
"label":"Pending",
"value":"Pending"
}
},
{
"billed_amount":111.70,
"claim_number": "1233514-5",
"location":"Springfield Hospital",
"member_id":"C1234567890",
"status":{
"label":"Pending",
"value":"Pending"
}
},
{
// ...etc
}
]
I am trying to loop through each row and put the property values in an array, one for each row so I can filter them against filterArr. How can I do that?
My question is similar to this post (From an array of objects, extract value of a property as array
), with the key difference being that I'm trying to create an array per object.
Each object represents a row in a table that I am trying to dynamically filter. So I can't have values from different rows being put into one array.
According to your desired result, I think you can use ES6 functions.
const result = yourTable.map(element => Object.values(element));
Using map() function, you go through all elements, and extract from each object its values.
Unsure what you want to include in your output but the below will loop through an array and return an array to the filter function
const output = claimTable["claims"].map((claim) => {
return claim
}).filter((claim) => {
return claim.billed_amount > 100
})
The above will loop through the claims and 'convert' to an array. The filter will return that claim for all true conditions (in this case, if the billed amount is greater than 100).
This article goes over this and adds a bit more to it.
I have an array with nested array
I want the data to append in a new array.
For the data extraction or filtration what method's i have to use, using library such as lodash
DATA
[
[
{
_id: 588d9b8a608f2a66c298849f,
email: 'sd#',
password: '$2a$10$6..L3c3tANi6ydt9gZbc1O6prPfUd3RB.ner5lilxRyEwo1lPsSoC',
isJobSeeker: true,
__v: 0,
lastName: 'shrestha',
firstName: 'manish',
isSeeker: true
}
],
[
{
_id: 588dbb4f7a48ce0d26cb99fd,
jobId: [Object],
seekerId: 588d9b8a608f2a66c298849f,
employerId: 588d7d6c0ec4512feb819825,
__v: 0,
}
]
]
REQUIRED DATA
[
{
_id: 588d9b8a608f2a66c298849f,
email: 'sd#',
password: '$2a$10$6..L3c3tANi6ydt9gZbc1O6prPfUd3RB.ner5lilxRyEwo1lPsSoC',
isJobSeeker: true,
__v: 0,
lastName: 'shrestha',
firstName: 'manish',
isSeeker: true
},
jobId: [{}, {}, {}] // ARRAY WITH OBJECTS
]
also i want to change the jobId key to other key of custom string as jobs
Following is my attempt:
console.log('Data filteration', data);
const filteredData = [];
filteredData.push(data[0][0]);
data[1].forEach((i) => {
filteredData[0].jobs = i.jobId
});
console.log('filteredData', filteredData);
First you should clean you data to have a better structure.
[
[
{ ... }
],
[
{ ... }
]
]
In this datastructure, its difficult to understand what does inner arrays signify. Instead you should use an object. That would define the purpose of array and make your code more readable.
var data=[[{_id:"588d9b8a608f2a66c298849f",email:"sd#",password:"$2a$10$6..L3c3tANi6ydt9gZbc1O6prPfUd3RB.ner5lilxRyEwo1lPsSoC",isJobSeeker:!0,__v:0,lastName:"shrestha",firstName:"manish",isSeeker:!0}],[{_id:"588dbb4f7a48ce0d26cb99fd",jobId:["test","test1"],seekerId:"588d9b8a608f2a66c298849f",employerId:"588d7d6c0ec4512feb819825",__v:0}]];
var cleanedData = {
userData: data[0],
userJobMap: data[1],
}
var result = cleanedData.userData.reduce(function(p,c){
if(c.isJobSeeker){
var job = cleanedData.userJobMap.filter(x=> x.seekerId === c._id);
// To copy object and not reference
var t = Object.assign({}, c, { jobId: job[0].jobId });
p.push(t)
}
return p
}, [])
console.log(result)
References
Array.map is a tool that iterates over all elements and return different value say a single property of return double value of all numbers in array. Note, this will yield an array of same size.
Array.filter on the other hand is use to filter array based on condition. This will return a subset of original data but elements will be same. You cannot change element structure.
Array.reduce is a tool that address cases where you need to return selected elements with parsed value. You can achieve same by chaining .filter().map() but then its an overkill as it would result in O(2n).
Object.assign In JS objects are passed by reference. So if you assign an object to a variable, you are not copying entire object, but only reference. So it you change anything in this variable, it will also reflect in original object. To avoid this, you need to copy value. This is where Object.assign comes. Note, its not supported by old browsers. For them you can check following post - What is the most efficient way to deep clone an object in JavaScript?
Note: All array functions are part of functional programming paradigm and are used to make your code more readable and concise but they come at an expense of performance. Traditional for will always perform faster then them. So if you want to focus on performance, always try to use for (though difference is very small but can add up for multiple cases and become substantial)
Basically I got my app up an running but I'm stuck with a problem: if I pass an object that contains an empty array to be saved, the array is not saved into the db. I'm not sure this is a problem in js or the mongo driver, but in order to save the empty array I need to pass the array like so: products: [''].
This is the structure of my mongo document:
_id: ObjectId(...),
name: 'String',
subcategories: [
{
subcategory: 'string',
products: [
{
name: 'string'
price: integer
}
]
}
]
So in my front-end I'm grabbing the whole document through an ajax call pushing a new object into the subcategories array. The new object looks like this:
{subcategory:'string', products:['']}
And this works okay until I need to insert a new object inside the array: Because I've grabbed the whole object, pushed the new object to the array, the previous one looks like this:
{subcategory: 'string'}
Having lost the mention to products:[] array in the process.
How can I get around this? I need to be able to have empty arrays in my object.
EDIT
What I did on front end: Got the whole object with $.get which returned:
var obj =
_id: ObjectId(...),
name: 'String',
subcategories: [
{
subcategory: 'Subcategory1',
products: [
{
name: 'string'
price: integer
}
]
}
];
Then on the front end I've pushed the new object category inside the subcategories array:
data.subcategories.push({subcategory: 'Subcategory2', products: ['']})
Where subcat was a string with the category name. On my db I could see that I've successfully added the object:
var obj =
_id: ObjectId(...),
name: 'String',
subcategories: [
{
subcategory: 'Subcategory1',
products: [
{
name: 'string'
price: integer
}
]
},
{
subcategory: 'Subcategory2'
products: []
}
];
The problem was when I wanted to add another subcategory, the previous one return empty:
var obj =
_id: ObjectId(...),
name: 'String',
subcategories: [
{
subcategory: 'Subcategory1',
products: [
{
name: 'string'
price: integer
}
]
},
{
subcategory: 'Subcategory2'
},
{
subcategory: 'Subcategory3'
products: []
},
];
Because at some point the empty array was removed from the object. Like I said, I did fix this in the front end, so the error jade was throwing has been addressed, but I still find odd that the products: [] was being removed from the document.
I'm new to MongoDb and node, not to mention that I'm also new with JS, so it might well be a feature that I'm unaware of.
When passing empty arrays to Mongo they are interpreted as empty documents, {}. Zend Json encoder will interpret them as empty arrays []. I understand that it's not possible to tell which one is correct.
Incase of empty arrays try posting as
Array[null];
instead of Array[];
This will be working fine
When passing empty arrays to Mongo they are interpreted as empty documents, {}. Zend Json encoder will interpret them as empty arrays []. I understand that it's not possible to tell which one is correct.
In my view it's more logical that the actual php array (when empty) is interpreted as an array in MongoDB. Although that will require something else to identify empty documents it's still more logical than the current behaviour.
A possible solution would be to introduce a new object, MongoEmptyObject (or using the stdObj) whenever one want to introduce an empty object.
Meanwhile, a workaround is to detect empty arrays in php, and inject a null value $arr[0] = null;
Then the object will be interpreted as an empty array in mongo.
The workaround works both in PHP and in the mongo console. Question: does json allow for arrays with null values? If so, then the workaround is a sign of another bug.
PHP:
if (is_array($value) && empty($value))
{ $value[0] = null; }
Mongo Console:
var b =
{hej:"da", arr: [null]}
db.test.save(b);
db.test.find();
{"_id" : "4a4b23adde08d50628564b12" , "hej" : "da" , "arr" : []}