Format array for batch api call in Javascript - javascript

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.

Related

How to use JSON response as an array in javascript

Here is my response I get from API request:
[ 'bookShelf3', 'bookShelf4', 'bookShelf5' ]
Here is a part of my code which searches through my mongoDB Databese:
const responseToSearchC = (req, res) => {
console.log(req.body.searchTerm);
db.collection('subtitle')
.find({
series: { $in: ['bookShelf1'] },
$text: { $search: req.body.searchTerm },
})
I just want to make my code dynamic and instead hard coding ['bookShelf1']
set its value by JSON response.
the problem is the response from API is an object (although it is look like an array) and I cannot replace it with my hard codded array ['bookShelf1']
I tried to stringify it but it didn't work cuz its a string again, and not an array like hardcoded one
If the response is really an object like:
{ 0: 'bookShelf3', 1:'bookShelf4', 2: 'bookShelf5'}
you can simply utilize the Object.values() method which returns all of the object's values as an array.
Here's an example:
let ob={ 0: 'bookShelf3', 1:'bookShelf4', 2: 'bookShelf5'};
console.log(Object.values(ob));

Is there a quicker way to copy a value in a key of data object to a new key in the same data object in javascript?

I'm experimenting with how I can make my code more concise when I have a piece of an array of objects received from an API endpoint. This is the initial variabel:
let stringOptionsOutlet = [];
Then I want to make a new key called "value". This is how I normally do (which I think is okey but I believe there must be some disadvantages in comparison with other techniques you might come up with):
stringOptionsOutlet = [...response.data.outlet]; // 1. this is the data I get from an API endpoint, I copy it with the spread operator
stringOptionsOutlet.map((v) => return { ...v, value: "" }; ); // 2. then I make the same new value in every single data object inside the array stringOptionsOutlet
Object.entries(stringOptionsOutlet).forEach((e) => {
e[1].value = e[1].id; // 3. copy the value of id to the new key
});
The data before I map the data:
[
{
label: "A1-1",
id: "1",
},
{
label: "B2-1",
id: "4",
},
]
After the mapping (step number 2 and number 3):
[
{
label: "A1-1",
id: "1",
value: "1",
},
{
label: "B2-1",
id: "4",
value: "1"
},
]
Could you also please explain the benefits and shortcomings of the techniques? Thank you.
What you're doing will work but there are certainly some unnecessary steps as written. There's no need to copy the API response data into an array and then change the array contents when you can map the API response itself.
// You can do steps 1 2 and 3 all in 1 .map()
const stringOptionsOutlet = response.data.outlet.map(v => {
return {
...v,
value: v.id
}
})
The downside of doing it all in 1 way is that if you want to do some more complex logic that single .map call could get very cluttered and maybe it'd be simpler to introduce a separate step, with the caveat that you'd then process the data a second time.
Try this:
stringOptionsOutlet.map((v) => ({ ...v, value: v.id }));

From single array convert to an array of object with keys coming from a JSON response -JAVASCRIPT-

I am receiving a json response from an API call. I need to store its keys, and create an array of an object. I am intending to this array of an object is created dynamically no matter the keys of the response.
I've already got the keys like this:
const json_getAllKeys = data => {
const keys = data.reduce((keys, obj) => (
keys.concat(Object.keys(obj).filter(key => (
keys.indexOf(key) === -1))
)
), [])
return keys
}
That returned an array (using a sample json):
['name','username', 'email']
But I am trying to use that array to create an array of object that looks like this one
[
{
name: "name",
username: "username",
email: "Email",
}
];
I've been trying mapping the array, but got multiple objects because of the loop, and I need a single one to make it work.
keys.map(i=>({i:i}))
[
{ i: 'id' },
{ i: 'name' },
{ i: 'username' },
{ i: 'email' }
]
Any hint would be useful!
Thanks in advance :D
What you're looking for is Object.fromEntries, which is ECMA2019, I believe, so available in Node >=14 and will be provided as a polyfill if you employ babel.
I can't quite discern what your reduce should produce, but given the sample input, I would write
const input = ['name','username', 'email'];
const result = Object.fromEntries(input.map(name => ([name, name])));
// result == { name: 'name', username: 'username', email: 'email' }
You're definitely on the right track. One thing to remember is the map function will return the SAME number of output as input. So in your example, an array of 3 returns an array of 3 items.
For this reason, map alone is not going to give you what you want. You may be able to map => reduce it. However, here is a way using forEach instead. This isn't a strictly functional programming style solution, but is pretty straight forward and depending on use case, probably good enough.
let keys = ['name','username', 'email'] //you have this array
const obj = {}; // empty object to hold result
keys.forEach(i => {
obj[i] = i; // set the object as you want
})
console.log(obj); // log out the mutated object
// { name: 'name', username: 'username', email: 'email' }

Parse data into separate, labeled arrays

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);

How to update the value of a single property within a state object in React.js?

So I have the following object structure:
const SamplePalette = {
id: 1,
name: "Sample Palette",
description: "this is a short description",
swatches: [
{
val: "#FF6245",
tints: ["#FFE0DB", "#FFA797"],
shades: ["#751408", "#C33F27"]
},
{
val: "#FFFDA4",
tints: ["#FFFFE1"],
shades: ["#CCCB83"]
},
{
val: "#BFE8A3",
tints: ["#E7FFD7"],
shades: ["#95B77E"]
}
]
}
Let's imagine that this object is managed by the state of my app like this:
this.state = {
currentPalette: SamplePalette,
}
My question is how would I go about updating the val property of a given swatch object in the swatches array? Or more generally - how do I only update pieces of this object?
I tried using the update helper as well as to figure out how Object.assign() works, however I've been unsuccessful and frankly can't really grasp the syntax by just looking at examples.
Also, since I'm going to be modifying this object quite a lot, should I look into maybe using Redux?
[EDIT]
I tried #maxim.sh suggestion but with no success:
this.setState(
{ currentPalette: {...this.state.currentPalette,
swatches[0].val: newValue}
})
Consider you have new new_swatches
I think the clearer way is to get array, update it and put back as:
let new_swatches = this.state.currentPalette.swatches;
new_swatches[0].val = newValue;
this.setState(
{ currentPalette:
{ ...this.state.currentPalette, swatches: new_swatches }
});
Also you have : Immutability Helpers or https://github.com/kolodny/immutability-helper
Available Commands
{$push: array} push() all the items in array on the target.
{$unshift: array} unshift() all the items in array on the target.
{$splice: array of arrays} for each item in arrays call splice() on the target with the parameters provided by the item.
{$set: any} replace the target entirely.
{$merge: object} merge the keys of object with the target.
{$apply: function} passes in the current value to the function and updates it with the new returned value.

Categories

Resources