How to create an Array from grabbing objects values from an API - javascript

Hello, I am trying to create an array of the data for height from an api as
[270, 1440, 1440, 1440, 1440] but am having trouble understanding how the process work.
I have tried using
var result = screenshots.map((ele) => ele.height)
, but I know you got to incorporate a key value like
screenshots.map((ele,key) => ele.height)
somehow.

Not exactly sure what your asking, but you can read up on how to use map here.
There is no "key" parameter, only: currentValue, index, and array.
Your example of how to create a "result" array for heights should work.
If you're trying to create an array of objects with a reduced set of keys, you could do something like this:
const result = screenshots.map(ele => ({
height: ele.height,
imageId: ele.image_id
}));
If you provided more clarify with regard to what you're asking, someone might be able to help you better.

Related

Javascript sorts object values

Hope you have been a good day. I want to ask you a question. Here is it:
So I have an object and I get values from it with Underscore.js (I will give you an example without using underscore.js to getting values).
After I get values, it puts numbers that are bigger than 0. I think it sorts bigger than smaller.
I want values exactly how they are at the object before I take them.
Here is an image for you
Here is the code
tmpReport.forEach(element => {
const tmpVal = [];
console.log("element: ", element);
tmpValList.push(_.values(element));
console.log('tmpValList: ', tmpValList);
});
Here is the code without using underscore.js:
tmpReport.forEach(element => {
const tmpVal = [];
console.log("element: ", element);
Object.entries(element).forEach(([key, value]) => {
tmpVal.push(value);
});
tmpValList.push(tmpVal);
console.log('tmpValList: ', tmpValList);
});
So any help will be appreciated. Thank you!
In JavaScript, the order of object entries is not guaranteed.
If you want to put specific entries at specific indices in your array you have to do that manually.
For example:
tmpVal[0] = element['Cell damage by placing'];
...
tmpVal[4] = element['time'];
tmpVal[5] = element['toplan'];
You can only achieve that if you are aware of your object keys. As far as I know there is now generic way to keep the initial order as there is no order to begin with.
The best you can do in that case is use a lexicographic order and sort your keys accordingly.

Prevent pushing to array if duplicate values are present

I'm mapping an array and based on data i'm pushing Option elements into an array as follows
let make_children: any | null | undefined = [];
buyerActivityResult && buyerActivityResult.simulcastMyAccount.data.map((item: { make: {} | null | undefined; }, key: any) => {
make_children.push(
<Option key={key}>{item.make}</Option>
);
});
Following data array has several objects and these objects have an attribute called model.
buyerActivityResult.simulcastMyAccount.data
I want to prevent pusing Options to my array if the attribute model has duplicate data. It only has to push once for all similar model values.
How can i do it?
I tried something like this
buyerActivityResult && buyerActivityResult.simulcastMyAccount.data.map((item: { model: {} | null | undefined; }, key: any) => {
model_children.indexOf(item.model) === -1 && model_children.push(
<Option key={key}>{item.model}</Option>
);
});
But still duplicate values are being pushed into my array.
Its difficult to tell what you are trying to achieve but it looks like a map may not be the right tool for the job.
A map returns the same sized length array as that of the original array that you are calling map on.
If my assumptions are correct, your buyerActivityResult.simulcastMyAccount.data array has duplicate values, and you want to remove these duplicates based on the model property? One way to achieve this would be to use the lodash library for this, using the uniq function:
const uniqueResults = _.uniq(buyerActivityResult.simulcastMyAccount.data, (item) => item.model);
The Array.prototype.map() method is supposed to be used for manipulating the data contained into the array performing the operation. To manipulate data from other variables I recommend to use a for-loop block.
If item.model is an object, the function Array.prototype.indexOf() always returns -1 because it compares the memory address of the objects and does not do a deep comparison of all properties values.
The usual solution to remove duplicate data from an array is converting the Array into a Set then back to an Array. Unfortunately, this works only on primary type values (string, number, boolean, etc...) and not on objects.
Starting here, I will review your source code and do some changes and explain why I would apply those changes. First of all, assuming the make_children array does not receive new attribution later in your code, I would turn it into a constant. Because of the initialization, I think the declaration is overtyped.
const make_children: any[] = [];
Then I think you try to do too much things at the same time. It makes reading of the source code difficult for your colleagues, for you too (maybe not today but what about in few weeks...) and it make testing, debugging and improvements nearly impossible. Let's break it down in at least 2 steps. First one is transforming the data. For example remove duplicate. And the second one create the Option element base on the result of the previous operation.
const data: { make: any }[] = buyerActivityResult?.simulcastMyAccount?.data || [];
let options = data.map((item) => !!item.model); // removing items without model.
// Here the hard part, removing duplicates.
// - if the models inside your items have a property with unique value (like an ID) you can implement a function to do so yourself. Take a look at: https://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript
// - or you can use Lodash library like suggested Rezaa91 in its answer
options = _.uniq(data, (item) => item.model);
Now you only have to create the Option elements.
for (var i = 0; i < options.length; i++) {
model_children.push(<Option key={i}>{options[i].model}</Option>);
}
// OR using the Array.prototype.map method (in this case, do not declare `model_children` at the beginning)
const model_children:[] = options.map((opt:any, i:number) => <Option key={i}>{opt.model}</Option>);
Despite the lack of context of the execution of the code you provided I hope my answer will help you to find a solution and encourage you to write clearer source code (for the sake of your colleagues and your future self).
PS: I do not know anything about ReactJs. forgive me my syntax mistakes.

Merge key/value into response.data inline?

This is probably a simple question, but my lack of JavaScript skills is probably preventing me from figuring out a one-liner to do this. Im using axios to request from an API, im getting a response back (This is for a "Todo" list app), however I need to merge another field into this response.
The snippet of code looks like this:
let mergedIsEditing = {...response.data, isEditing: false}
const lists = [ ...this.state.lists, mergedIsEditing ]
lists is basically what it sounds like (an array of lists), and the response.data is nothing more than an object with a title and description. I thought maybe using Object.assign but since im already spreading out this.state.lists im not sure how that would work. Essentially I just need to add the key/value pair isEditing: false onto that list coming in.
Not to encourage shorter code over readability, but to answer your question, this is how you could do the equivalent to your snippet in 1 line:
let mergedIsEditing = {...response.data, isEditing: false}
const lists = [ ...this.state.lists, mergedIsEditing ]
const lists = [ ...this.state.lists, {...response.data, isEditing: false} ]
Of course, you could prepend this.state.lists =, if that's the desired purpose.

Get data from an array of dictionaries in Javascript

I'm working with a web framework and I'm using variables from Python into Javascript code.
I get next array in Python, which can contain more than one cell with dictionaries inside it:
[[{'lacp_use-same-system-mac': u'no'}, {'lacp_mode': u'passive'}, {'lacp_transmission-rate': u'slow'}, {'lacp_enable': u'no'}]]
I want to be able to access every cell array and, after that, get every keys from the dictionary inside this cell array. Up to now, I only have arrays or dictionaries, so for both cases I did next:
var X = JSON.parse(("{{X|decodeUnicodeObject|safe}}").replace(/L,/g, ",").replace(/L}/g, "}").replace(/'/g, "\""));
Where X is the Python variable. Unfortunately, this does not run with the array I wrote above.
How can I do that?
Thanks beforehand,
Regards.
I want to be able to access every cell array and, after that, get
every keys from the dictionary inside this cell array
If I understood correctly you want to get the keys of a nested array.
Note: your array isn't valid js.
const arrarr = [[{key1: 'val1'}, {key2: 'val2'}], [{key3: 'val3'}, {key4: 'val4'}]];
arrarr.forEach(arr => {
arr.forEach(e => {
Object.keys(e).forEach(k => console.log(k))
})
})
If the depth of nests is of arbitrary depth you can use recursion and check if the child is an array, if it is keep going, else get the keys.

How To Efficiently Extract Certain Information From A POJO

I am working a lot with firebase, and am trying to load certain information from the database. The original data comes from a query, and is returned to me in a POJO. The console prints this when the original data is returned:
-KhQ76OEK_848CkIFhAq: "-JhQ76OEK_848CkIFhAq"
-OhQ76OEK_848CkIFhAq: "-LhQ76OEK_848CkIFhAq"
What I need to do is grab each of the values (-JhQ76OEK_848CkIFhAq and -LhQ76OEK_848CkIFhAq) separately, and query the real-time database again for each one. I can manage that aspect, but I cannot seem to figure out how to separate the values.
I have already tried to get a single output by doing:
console.log(vals[0]) but it just returned undefined, and splitting the string by " would be very inefficient for large data sets. Any ideas?
To access the values, you can iterate the snapshot's children using the snapshot's forEach method. The keys and values of the children can be obtained using the key property and the val() method:
firebase.database()
.ref("some/path")
.once("value")
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.key); // The child's key: e.g. "-KhQ76OEK_848CkIFhAq"
console.log(childSnapshot.val()); // The child's value: e.g. "-JhQ76OEK_848CkIFhAq"
});
});
To solve this issue, all I did was convert the object returned into an array by using this code below:
var Array = Object.keys(datalist).map(function(k) { return datalist[k] });
Works like a charm, and I can now run a simple for loop for Array

Categories

Resources