I'm stuck working on something and need help. I want to find a word in a path and use it as an object.
I mean, there is array like this;
routes : [
0: {
...
path : 'x/x/create'
... }
1: {
...
path : 'y/y/y'
... }
]
and I want to use object with path : 'x/x/create'. And of course it s not always in the first place.
*Edit: x always changing so I need to find 'create' word
routes.find(i => i.path.includes('create')).word;
Try using Array.find
const routes = [
{ path: 'x/x/create' },
{ path: 'y/y/y' },
]
console.log(routes.find((route) => route.path === 'x/x/create'));
console.log(routes.find((route) => route.path === '/create'));
const routes = [
{
id: 1,
path: "x/x/create"
},
{
id: 2,
path: "y/y/y"
}
]
const result = routes.find(i => {
if (i.path.split('/')[2] === 'create') return i.id;
});
console.log(result); //{id:1, path:"x/x/create"}
Related
eslint keeps showing me a prefer-restructuring error. However, I'm don't really know how array destructuring works and would love some help.
These are the two lines returning an error:
word.results.inCategory = word.results.inCategory[0];
// and:
word.results = word.results.filter(
(res) =>
Object.keys(res).includes('partOfSpeech') &&
Object.keys(res).includes('inCategory')
)[0];
Again, I'm not very knowledgable in this area, so any help on how to fix/simplify this specifically would be appreciated!
EDIT: Here is an example object for reference:
{
word: 'midrash',
results: [{
definition: '(Judaism) an ancient commentary on part of the Hebrew scriptures that is based on Jewish methods of interpretation and attached to the biblical text',
partOfSpeech: 'noun',
inCategory: ['judaism'],
typeOf: [ 'comment', 'commentary' ]
},
{
definition: 'something',
partOfSpeech: 'something',
}],
syllables: { count: 2, list: [ 'mid', 'rash' ] },
pronunciation: { all: "'mɪdrɑʃ" },
frequency: 1.82
}
To get the value of inCategory you should use the destructuring assignment as follow:
const obj = {
word: 'midrash',
results: {
definition: '(Judaism) an ancient commentary on part of the Hebrew scriptures that is based on Jewish methods of interpretation and attached to the biblical text',
partOfSpeech: 'noun',
inCategory: 'judaism',
typeOf: [ 'comment', 'commentary' ]
},
syllables: { count: 2, list: [ 'mid', 'rash' ] },
pronunciation: { all: "'mɪdrɑʃ" },
frequency: 1.82
}
let {results: {inCategory: category}} = obj;
//Now you can assign the category to word.results.inCategory
console.log(category);
For the filter approach, I suggest using the function Array.prototype.find
word.results = word.results.find(
(res) =>
Object.keys(res).includes('partOfSpeech') &&
Object.keys(res).includes('inCategory')
);
If you are already sure that your data structure is correct and both word.results.inCategory and word.results are arrays then this is how you do it:
const { results:{ inCategory: [inCategory] }} = word;
word.results.inCategory = inCategory;
// and:
const [results] = word.results.filter(
(res) =>
Object.keys(res).includes('partOfSpeech') &&
Object.keys(res).includes('inCategory')
);
word.results = results;
Of course in the second destructing when you filter you can just use find that allows you directly set the word.results without destructing:
word.results = word.results.find(
(res) =>
Object.keys(res).includes('partOfSpeech') &&
Object.keys(res).includes('inCategory')
);
I'm using the following:
Node.js: 9.8.0
Jest: 22.4.2
There's an array like the following being returned from myFunction:
[
...
{
id: 00000000,
path: "www.someUrl.com/some/path/to"
}
...
]
And I want to match it against the following kind of array:
const output = [
...
{
id: 00000000,
path: "path/some/path/to"
}
...
]
In a nutshell: I want to totally match the id, but only partially the path.
But I just don't know how... I've tried the following:
expect(myFunction()).toEqual(expect.arrayContaining(output));
But the gives me an error.
I've solved with the following code:
const output = JSON.parse(readFileSync('./myFunction.json', 'utf8'));
describe('Testing myFunction.', () => {
test('Deafult test.', () => {
const input = myFunction();
input.map((value, index) => {
const { imageURL, ...remaining } = output[index];
expect(value).toMatchObject({
...remaining,
imageURL: expect.stringContaining(imageURL)
});
});
});
});
I have an array of objects and another array of names like the following:
array of objects as file info objects
[
{ fieldname: 'banner', path: 'banner_img_path' },
{ fieldname: 'logo' , path: 'logo_img_path' },
{ fieldname: 'random', path: 'random_img_path' }
]
and here is my array of names
['banner', 'logo']
So how can i match or mapping those two variables! note that after mapping or matching, all not used objects should be deleted from the original array of objects?? i need to get object like that
{
banner: banner_img_path,
logo : logo_img_path
}
I'm able to do matching but i was stuck with erasing those not used objects.
Note: May be this question is duplicated but only because i don't know what is the name of this operation!
so please forgive me.
There is a simple solution by using functional native JavaScript functions.
const obj = [
{ fieldname: 'banner', path: 'banner_img_path' },
{ fieldname: 'logo', path: 'logo_img_path' },
{ fieldname: 'random', path: 'random_img_path' },
{ fieldname: 'other', path: 'random_img_path' }
];
const names = ['banner', 'logo'];
obj.map((o, i) => {
let match = false;
names.some((item) => {
if (item === o.fieldname) {
match = true;
return true;
}
});
if (!match) {
delete obj[i];
}
});
for (let o in obj) {
document.querySelector('p').innerHTML += obj[o].fieldname + '<br>';
}
<p></p>
I add the names you want to keep into a set for lookup. I then use forEach and check inside each object if the fieldname matches anything in the set of names. If there's a match, I add it to my newObj.
const namesToKeep = ['banner', 'logo']
const fileInfo = [
{ fieldname: 'banner', path: 'banner_img_path' },
{ fieldname: 'logo' , path: 'logo_img_path' },
{ fieldname: 'random', path: 'random_img_path' }
]
const names = new Set(namesToKeep)
const newObj = {}
fileInfo.forEach(obj => {
if (names.has(obj.fieldname)) {
newObj[obj.fieldname] = obj.path
}
})
console.log(newObj)
I have two values I need to match as you can see in the picture below:
I tried something like this:
const index = state.locks.users.findIndex(
stateUser => stateUser._id === action.payload.customerPayload.accessid
But I’m getting the error:
findIndex of undefined.
And I guess that’s because of locks being an array.
But I’m really uncertain how to fix this issue. Should I have multiple findIndexes? One for the lock and one for to match the users?
Thanks for reading my post. And I appreciate all the help I can get.
The code snippet should be
let itemIndex = -1;
state.locks.map((lock) => {
lock.users.findIndex(...)
});
Assuming state is an object containing locks array.
My suggestion to you is do a double for loop (as you've already figured) to get the user object that you need.
Consider the following snippet (adjust to your data structure):
let state = {
locks: [
{
users: [
{ _id: '123' },
{ _id: '456' }
]
},
{
users: [
{ _id: '678' },
{ _id: '789' }
]
},
]
};
function getUserObjByID(stateObj, userID) {
for (let usersObject of state.locks) {
for (let user of usersObject.users) {
if (user._id === userID) {
return user;
}
}
}
}
let myObj = getUserObjByID(state, '678');
console.log(myObj);
So it works now. What I had to do with my reducer was this:
case 'REMOVE_USER':
return {
...state,
locks: state.locks.map(lock => {
return {
...lock,
users: lock.users
? lock.users.filter(
user => user._id != action.payload.customerPayload.accessid
)
: []
}
})
}
I have object
var routes = {
"home":{
hash: "/home",
children: {
"just-home": {
hash: "/home/just-home",
children: {...}
},
"sub-homea": {
hash: "/home/sub-homea",
children: {...}
}
},
"contact":{
hash: "/contact",
children: {
"just-contact": {
hash: "/contact/just-contact",
children: {...}
},
"sub-contact": {
hash: "/contact/sub-contact",
children: {...}
}
}
}
How i can set object to just-contact.children when i know for example - that first key is contact, and next just-contat.. ? I need to assign this object dynamically because the known keys will be all time different. So i need use any loop. something like this -
const pathArray = [contact,just-contact]
Object.keys(routes).map(function (item) {
if (routes[item] === pathArray[counter]){
ob = routes[item];
counter++;
}
})
but this will loop only once and it won't go to deep.
UPDATE for more clean explanation -
I will read from path location (localhost:3000/contact/just-contact) the values (contact,just-contact) , which i will save to array (pathArray=[contact,just-contact]), when the location path will be change, the keys in array will be change too. And i need to find children of last key, in this example children of just-contact key
Found simple solution -
pathArray.map(function (item) {
if (obj[item].hash === item){
obj = obj[item].children;
}
})