Fuse.js to search in array with dot in keys - javascript

Im using fetch on a Rest endpoint which gives me a array of objects. All the keys in the array has a dot in them. ex: {test.name: "test"}. I have to keep fetching new responses to get changes so while i can remove or replace the dot this will take some time/resources every time. Is there any way to use keys with dots in fuse.js?
I tried some variants of this with no luck.
const fuse = new Fuse(this.state.test, {
keys: ['test.name']
});
ps. I cant change the keys in the Rest as its external

As of Fuse.js v6.3.0 you can search through nested values by providing the path via dot (.) or array notation. Therefore, if your key already has a dot in it, you can wrap it in an array:
const fuse = new Fuse(this.state.test, {
// `test.name` is the actual key, so wrap it in an array
keys: [['test.name']]
});

Related

In javascript how to replace elements of an array to it's corresponding values in another object?

I have the mapping of abbreviation and full name as follow:
object = {"TSLA":"TESLA INC.","GOOG":"GOOGLE INC.","APPL":"APPLE INC.","AMZN":"AMAZON CORPORATION", "MSFT":"MICROSOFT CORPORATION"}
as an output of function i get the following array:
array = ["AMZN","APPL"]
I want to display the values of the associated keys as follows:
output_array = ["AMAZON CORPORATION", "APPLE INC."]
Note that, the actual object has more key: value pairs
Using IndexOf() I can replace one value. However, I believe there must be a way of mapping the array elements to replace the values at once.
Since I am new to JS, I would appreciate any suggestion.
array.map(abbr => object[abbr]) does the job; it iterates over the array rather than the object, which is more efficient as the object already is a lookup table with the right keys - you are right, there is no need to use indexOf which uses a linear search.

Passing associative array as props not working

I have a React application which handles rooms and their statistics.
Previously, I had the code set up to pass as props to the next component:
the raw statistics (not a concern for the question)
an array of all the rooms set up as follows
I figured it would be simpler for me, though, to have the list of all rooms as an associative array where the keys of each element is the same as the ID it contains. To do that, I utilized a code similar to this in a for loop:
roomsList[rooms[v].ID] = rooms[v];
So that the result would be:
[a001: {...}, a002: {...}, ...]
I then proceeded to pass this style of array, and not the standard one with a numeric index, as a prop to the next component as such:
<StatsBreakdown stats={computedStats.current} roomsList={roomsList} />
BUT
Now, the next component sees that prop as an empty array.
Even more weirdly, if I initialize that roomsList array with a random value [0] and then do the same process, I end up with:
I cannot cycle through the array with .map, and, according to JS, the length is actually 0, it's not only Google Chrome.
Is there something I'm missing about the way JSX, JS or React work?
Your original roomsList was an array of objects, whose indices were 0,1,2 etc. roomsList[rooms[v].ID] = rooms[v]; implies you are inserting elements not using a number but an alphanumeric string. Hence your resulting array is no longer an array but an object.
So we can cycle over the object using Object.keys().
const renderRoomDets = Object.keys(roomsList).map(room => {
roomOwner = roomsList[room].owner_id;
return (
<div>
<p>{`Room Owner ${roomOwner}`}</p>
</div>
);
});
But I believe your original form is ideal, because you are reaping no special benefits from this notation.
A better alternative maybe using .find() or .findIndex() if you want iterate over an array based on a specific property.
const matchedRoom = roomsList.find(room => room.ID === 'Srf4323')
Iterate the new array using its keys not indexes.
Or even better store your data in an actual object instead of an array since you're using strings for ids.
First define your object like so:
let data = {};
Then start adding records to it. I'd suggest deleting the ID attribute of the object since you're storing it in the key of your record, it's redundant, and it won't go anywhere unless u delete the entry.
data[ID] = row;
To delete the ID attribute (optional):
row.ID = null;
delete row.ID;
Then iterate through it using
for(let key in data){}

Access a nested array in Angular 6

So i am attempting to access an Array of objects within a JSON object. I have an API that i am grabbing data from. The API was initially an XML and i converted it to a JSON object, however one i have dashes in my element names. (dang), but i also want to pull from the list of products. Below is an example of the API structure.
The goal is to get the list of products from the API.
Thanks to PXLJoy i was able to come up with the following solution. Note: I am using RXJS 6, therefore everything is wrapped in a pipe.
public getData(): Observable<any> {
const cjData = this.http.get('/assets/json/name.json');
return cjData.pipe(map(res => res['cj-api'].products[0].product));
}
Accessing properties in JSON can be done with [] square brackets, these are often used for variable keys, i.e
const key = 'cj-api';
const obj = response[key];
or string keys, i.e
const obj = response['cj-api'];
With that said, based on your screenshot, you could get the products array by going:
// response is the object as shown in your screenshot.
response['cj-api'].products[0].product; // your target array

How do I store a list of items referenced by key in javascript?

I need to be able to store a collection of items in javascript. I need to be able to delete them by key. This is a crud application. What's the best way to do this?
Do I need to remove the item with a splice from a standard array and then update the array to remove the missing space?
From your question is sounds like you are trying to do this using an array. It would be a lot easier to use an object as a key-value store. E.g.,
var collection = {};
Then, to add an item with a key:
collection[key] = item;
To get an item:
var item = collection[key];
And to delete an item:
delete collection[key];
If you want things to be easy, it is important to use a strings for keys. A key will be implicitly converted to a string using .toString(). This does not yield a useful result (unless overridden) if you try using an object as a key because it will be converted to the string "[object Object]".

Joining values in an Javascript array

Say I have:
var Certificated = {}
Sub items are added dynamically and variate. Possible outcome:
var Certificated = {
Elementary: ["foo","bar", "ball"]
MiddleSchool: ["bar", "crampapydime"]
};
I want to do the following:
Certificated.Elementary = Certificated.Elementary.join("");
Except I need it to do that on all of the objects inside.
Keep in mind I can't know for sure the titles of nor how many objects will be inside Certificated.
My question is how can I use .join("") on all elements inside Certificated, without calling each one specifically?
EDIT: I am aware .join() is for arrays and the objects inside Certificated are going to be arrays. Therefore the join method.
Does this work?
for (var key in Certificated) {
if (Certificated.hasOwnProperty(key)) {
Certificated[key] = Certificated[key].join("");
}
}
It loops through all properties of Certificated, and makes a quick safe check for the key being a real property, then uses bracket notation - [""] - to do your join.
Quick question - are you sure you want to use join? I know you just provided an example, but you can't call join on a string...it's for arrays. Just wanted to make sure you knew.
Here's a jsFiddle of my code working with arrays being used for the properties:
http://jsfiddle.net/v48dL/
Notice in the browser console, the properties' values are strings because the join combined them with "".

Categories

Resources