How to search within the nested array of objects in javascript? - javascript

i want to search a for a string say for example "hello" within 'name' in array of objects. The data structure is like the one below,
[{name:'hello', value: 'value', children: [{ name:'world', value: 'something'}]},
{name:'somename', value: 'value2', children: [{name: 'hello', value: 'value3', children: [{name: 'anothername', value: 'value4'}]},
{name: 'new', value: 'value5'}];
So from the above mentioned data structure, if the search query is say 'hello' i want to check through 'name' field of each object. also check within children 'name' field of each object. Some object may or may not have children and nested children too. I want to retreive the objects that have matched the search query.
For example if my search query is 'hello' then the expected output is as below,
[{name:'hello', value: 'value', children: [{ name:'world', value: 'something'}]},
{name:'somename', value: 'value2', children: [{name: 'hello', value: 'value3', children: [{name: 'anothername', value: 'value4'}]},
i have tried using the below search method but that doesnot search within children and nested children.
search = (query, listitems => {
if (!query) {
return listitems;
}
query = query.toLowerCase();
const results = [];
let counter;
let childcounter;
listitem.forEach((listitem) => {
counter = 0;
childcounter = 0;
if (listitem['name'].toLowerCase().indexOf(query) > -1)
{
counter++;
if (listitem.children)
{
listitem.children.forEach ((child) => {
if (child['name'].toLowerCase().indexOf(query) > -1)
childcounter++;
});
}
listitem.counter = counter;
listitem.childcounter = childcounter;
results.push(listitem);
}
return result
});
How can i do it. could someone help me with it. Thanks.

Related

Not able to save object value in Angular component

This is component class for example:
export class AppComponent {
categories = {
country: [],
author: []
}
constructor(){}
getOptions(options) {
options.forEach(option => {
const key = option.name;
this.categories[key].push(option.value);
})
}
}
On clicking a button, I am calling getOptions(options) from different component. The structure of options looks like:
options = [
{name: 'country', value: 'Germany'},
{name: 'author', value: 'Franz Kafka'}
]
So now the value of this.categories will get updated, so now:
this.categories[country] = ["Germany"]
this.categories[author] = ["Frank Kafka"]
Value of options changes every time on clicking the button. When I am sending new options value such as:
options = [
{name: 'country', value: 'Japan'},
{name: 'author', value: 'Masashi Kishimoto'}
]
Old value for this.categories[country] is not getting saved for some reason. The new value for this.categories[country] should be ["Germany, "Japan"] but I am getting only ["Japan"] in the array.
I don't seems like the code is alright, even I tried through Javascript. What I can suggest is try checking the truthy value of options.value. It could be a possibility that there is some entry with no value options.
let categories = {
country: [],
author: []
}
let options = [
{name: 'country'},
{name: 'author', value: 'Franz Kafka'},
{name: 'country', value: 'Japan'},
{name: 'author', value: 'Masashi Kishimoto'}
]
options.forEach(option => {
const key = option.name;
console.log(key);
if(option.value)
categories[key].push(option.value);
})
console.log(categories);

JavaScript Get Indexes based from the Selected Array of Object Id

Today, I'm trying to get the list of javascript index based from the selected data id that I have.
I'm following this guide from https://buefy.org/documentation/table/#checkable where it needs something like this: checkedRows: [data[1], data[3]] to able to check the specific row in the table.
What I need to do is to check the table based from my web API response.
I have this sample response data.
response.data.checkedRows // value is [{id: 1234}, {id: 83412}]
and I have the sample data from the table.
const data = [{
id: 1234,
name: 'Jojo'
},{
id: 43221,
name: 'Jeff'
},{
id: 83412,
name: 'Kacey'
}]
So basically, I need to have something, dynamically, like this: checkedRows: [data[0], data[2]] because it matches the data from the response.data.checkedRows
So far, I tried using forEach
let selectedIndex = [];
response.data.checkedRows.forEach((d) => {
this.data.forEach((e) => {
if (d.id=== e.id) {
// need the result to be dynamic depending on the response.data.checkedRows
this.checkedRows = [data[0], data[2]]
}
});
});
I'm stuck here because I'm not sure how can I get the index that matches the selected checkedRows from response.
Any help?
Map the response checkedRows, and in the callback, .find the matching object in the array:
const checkedRows = [{id: 1234}, {id: 83412}];
const data = [{
id: 1234,
name: 'Jojo'
},{
id: 43221,
name: 'Jeff'
},{
id: 83412,
name: 'Kacey'
}];
const objs = checkedRows.map(({ id }) => (
data.find(obj => obj.id === id)
));
console.log(objs);
If there are a lot of elements, you can use a Set of the IDs to find instead to decrease the computational complexity:
const checkedRows = [{id: 1234}, {id: 83412}];
const data = [{
id: 1234,
name: 'Jojo'
},{
id: 43221,
name: 'Jeff'
},{
id: 83412,
name: 'Kacey'
}];
const ids = new Set(checkedRows.map(({ id }) => id));
const objs = data.filter(obj => ids.has(obj.id));
console.log(objs);

How do we remove particular object from js Map object?

I have some objects inside js Map object. How do we remove object with particular key and value?
let newMap = new Map()
newMap.set('1', {ep: '1', name: 'First test'})
newMap.set('2', {ep: '2', name: 'Second test'})
So, the above example holds two object inside newMap. How can I remove object with ep value '1', so that the newMap hash returns only one object i.e. {ep: '2', name: 'Second test'}.
You've stored it under the key '1'. So you call delete with that key:
newMap.delete('1');
If you don't know the key you've stored it under, a Map probably isn't the structure you wanted, but you can find it by looping through entries, which returns an array whose entries are arraysin [key, value] format:
for (const entry of newMap.entries()) { // for-of is ES2015+
if (entry[1].ep === '1') {
newMap.delete(entry[0]);
break;
}
}
...or with ES5:
newMap.entries().some(function(entry) {
if (entry[1].ep === '1') {
newMap.delete(entry[0]);
return true;
}
});
You'll have to iterate over the entries and find the object you want to remove, then delete the appropriate key:
let newMap = new Map();
newMap.set('1', {ep: '1', name: 'First test'});
newMap.set('2', {ep: '2', name: 'Second test'});
const entryToRemove = [...newMap.entries()].find(([, { ep }]) => ep === '1');
newMap.delete(entryToRemove[0]);
console.log(newMap); // look in browser console, not snippet console
(Of course, if you can count on the map's key being the same as the ep, just do newMap.delete(epToDelete))
Your map looks like this:
Map { '1' => { ep: '1', name: 'First test' }, '2' => { ep: '2',
name: 'Second test' } }
To remove ep:'1' and have onlye ep:'2' you can try this:
newMap.delete('1');

json object from javascript nested array

I'm using a nested array with the following structure:
arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";
now I'm trying to get a nested Json Object from this array
arr{
{
id: example0,
name: name00,
},
{
id: example1,
name: name01,
},
{
id: example2,
name: name02,
}
}
I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.
Thank you!
If you are starting out with an array that looks like this, where each subarray's first element is the id and the second element is the name:
const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]
You first need to map it to an array of Objects.
const arrayOfObjects = array.map((el) => ({
id: el[0],
name: el[1]
}))
Then you can call JSON.stringify(arrayOfObjects) to get the JSON.
You need to make a valid array:
arr = [
{
id: 'example0',
name: 'name00',
},
{
id: 'example1',
name: 'name01',
},
{
id: 'example2',
name: 'name02',
}
];
console.log(JSON.stringify(arr));
Note that I am assigning the array to a variable here. Also, I use [] to create an array where your original code had {}.

AngularJS : How to concat two arrays?

I have following arrays with values (i am generating the values on go)
$scope.objectName = [{ Name: '' }];
$scope.propertiesElement = [{ Key: '', Value: '' }];
I want to concatenate these two objects to get the following result
[{Name:''},{ Key: '', Value: '' }]
Plunker link , somehow that's not working either
when I click on the add row button it will add another row for key and value text boxes only not for name, I can add n no of rows and when I click on Submit it should show the kev value pair as
[{Name:''},{ Key: '', Value: '' },{ Key: '', Value: '' },{ Key: '', Value: '' }.....so on]
Thanks
Not sure why you want to build an array of mismatched objects. That seems to me to be asking for trouble. I would suggest possibly doing the following:
$scope.objects = [{Name: '', Elements: []}];
Then you can easily manage multiple objects who have elements:
(I use underscore http://underscorejs.org/)
$scope.addElementToObject = function(objName, element){
_.where($scope.mergedArray, {Name: objName}).Elements.push(element);
};
Then you can add to the list of elements for that object without having to eval the object in the elements array on each use.
If you still want/need to merge arrays of mismatched objects, it would be the following:
$scope.objectName = [{ Name: '' }];
$scope.propertiesElement = [{ Key: '', Value: '' }];
$scope.mergedArray = $scope.objectName.contact($scope.propertiesElement);
$scope.addElement = function(element){
$scope.mergedArray.push(element);
};
Then, in your click event code:
$scope.addElement({ Key: 'someKey', Value: 'Some Value' });
I hope this helps.

Categories

Resources