JAVASCRIPT Search in 3D array of objects [duplicate] - javascript

This question already has an answer here:
Search in multi dimension Array in JAVASCRIPT [closed]
(1 answer)
Closed last year.
I have an array with some data like this :
const
data = [
{"key":9054,"title":"1","children":[
{"key":8959,"title":"1-0","idFather":8959,"tableIsFamily":false,"children":[]},
{"key":8943,"title":"1-1","idFather":8943,"tableIsFamily":false,"children":[]},
{"key":9021,"title":"1-2","idFather":9021,"tableIsFamily":false,"children":[]},
{"key":8969,"title":"1-3","idFather":8969,"tableIsFamily":false,"children":[]}]},
{"key":9040,"title":"2","children":[
{"key":8957,"title":"2-0","idFather":8957,"tableIsFamily":false,"children":[]},
{"key":8941,"title":"2-1","idFather":8941,"tableIsFamily":false,"children":[
{"key":8947,"title":"2-1-0","idFather":8941},
{"key":9855,"title":"2-1-1","idFather":8941}
]},
{"key":8949,"title":"3-0","idFather":8949,"tableIsFamily":false,"children":[]},
{"key":8983,"title":"3-1","idFather":8983,"tableIsFamily":false,"children":[]},
{"key":10070,"title":"3-2","idFather":10070,"tableIsFamily":false,"children":[]}
]}
];
And I have another array with some Id's like this :
[9054, 9021, 9040, 8941, 8947]
I want to filter the data array and get only matched array with the second array, I have tried some map/filter but it seem to be more difficult thann i think, Have you any ideas how to deal with this array please ?
The expected output should be :
const
data = [
{"key":9054,"title":"1","children":[
{"key":9021,"title":"1-2","idFather":9021,"tableIsFamily":false,"children":[]},
{"key":9040,"title":"2","children":[
{"key":8941,"title":"2-1","idFather":8941,"tableIsFamily":false,"children":[
{"key":8947,"title":"2-1-0","idFather":8941},
]},
]}
];
Thank you!

You can use rectursive function for deep datas. Like this.
This function can also be used for deeper structures.
Further information about the recursive function here: https://www.geeksforgeeks.org/recursive-functions/#:~:text=In%20programming%20terms%2C%20a%20recursive,can%20be%20solved%20quite%20easily.
const
data = [
{"key":9054,"title":"1","children":[
{"key":8959,"title":"1-0","idFather":8959,"tableIsFamily":false,"children":[]},
{"key":8943,"title":"1-1","idFather":8943,"tableIsFamily":false,"children":[]},
{"key":9021,"title":"1-2","idFather":9021,"tableIsFamily":false,"children":[]},
{"key":8969,"title":"1-3","idFather":8969,"tableIsFamily":false,"children":[]}]},
{"key":9040,"title":"2","children":[
{"key":8957,"title":"2-0","idFather":8957,"tableIsFamily":false,"children":[]},
{"key":8941,"title":"2-1","idFather":8941,"tableIsFamily":false,"children":[
{"key":8947,"title":"2-1-0","idFather":8941},
{"key":9855,"title":"2-1-1","idFather":8941}
]},
{"key":8949,"title":"3-0","idFather":8949,"tableIsFamily":false,"children":[]},
{"key":8983,"title":"3-1","idFather":8983,"tableIsFamily":false,"children":[]},
{"key":10070,"title":"3-2","idFather":10070,"tableIsFamily":false,"children":[]}
]}
];
const ids = [9054, 9021, 9040, 8941, 8947]
filterData = (data)=> {
const newData = data.filter((obj)=>ids.includes(obj.key));
newData.forEach((obj)=>{obj.children ? obj.children = filterData(obj.children) : []});
return newData;
}
console.log(filterData(data));

Related

Adding key value to inner array in a multidimensional array when key doesn't exist (javascript) [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 months ago.
I need to develop a function whereby a type property gets appended to an array if it doesn't exist.
So the key will be of type and it should have a value of "dog".
Can someone kindly point out how I can iterate over the array to check if the key "type" exists and also provide guidance on how to append {type:"dog"} to the inner array if it doesn't exist. I tried animalArray[0][1]={type:"dog"} but it doesnt seem to work.
A typical array of animals will look like this:
labelTheDogs(
[
{name: 'Obi'},
{name: 'Felix', type: 'cat'}
]
)
// should return [
{name: 'Obi', type: 'dog'},
{name: 'Felix', type: 'cat'}
]
This is not a nested array
function labelTheDogs(dogs) {
dogs.forEach(dog => {
if (!dog.type) {
dog.type = 'dog'
}
})
return dogs
}
const dogs = labelTheDogs(
[{
name: 'Obi'
},
{
name: 'Felix',
type: 'cat'
}
]
)
console.log(dogs)
you can use the map function to do that
const newArray = yourArray.map((element) => {
if(!element.type){
element.type = "dog";
}else {
return element
}
})

Find the element in json - Using underscore library or other way

I want to find the g:id object in the below given array of objects
If my g:id is like "g:id": "121"
I can find the element like
var item = _.findWhere(obj, {'g:id': '121'});
But what i have is "g:id": ["121"] like an array. How can i find it.
Here's my array of objects.
[
{
"g:id": [
"121"
],
"g:item_group_id": [
"90461"
]
},
{
"g:id": [
"129"
],
"g:item_group_id": [
"90462"
]
}
]
I tried like this var item = _.findWhere(jsonXML, {'g:id'.[0]: '121'}); but it is not valid.
How can i do this by underscore.js or any other way ?
You can use Array.find() with destructuring to get the g:id value from the array:
const arr = [{"g:id":["121"],"g:item_group_id":["90461"]},{"g:id":["129"],"g:item_group_id":["90462"]}]
const result = arr.find(({ 'g:id': [gid] }) => gid === '121')
console.log(result)
Another option is to use Array.includes() to see if the array contains the value (a must if the array may contain more the one value):
const arr = [{"g:id":["121"],"g:item_group_id":["90461"]},{"g:id":["129"],"g:item_group_id":["90462"]}]
const result = arr.find(({ 'g:id': gid }) => gid.includes('121'))
console.log(result)

How to filter an array of objects by filtering an array inside of it in javascript

I'm trying to make an advanced searching for my app, it has a stores array of objects, every store is an object and every store has an array of objects that holds the items of that store, (every item is an object). (i'll leave the stores array down so u understand what i mean)
So basically, I want the user to filter the stores by the item names, but i got stuck and whatever i tried didn't seem to be working.
here is the code:
stores array:
let stores = [
{
name:"",
type:"",
items:[
{name:"tomato", quantity:"145", unit:"g"}, //this is what i want to filter with
{name:"other items here", quantity:"45", unit:"kg"},
{name:"example item", quantity:"74", unit:"l"},
]
}
]
The filtering way I've tried:
let userInput = "tomato";
//this outputs the original array without any filtering
let filteredStores = stores.filter(store=>{
return store.items.filter(item=>{
return item.name.includes(userInput)
})
})
Hope someone understands how i want to filter the stores, thanks
Array#filter will return an empty array when no matches are found. This is a truthy value, you can find this by doing !!array.filter(() => false). You need to call .length on the second filter to be able to determine whether it has found any matches or not, 0 is falsey and anything else is truthy.
You can try this:
let stores = [
{
name:"",
type:"",
items:[
{name:"tomato", quantity:"145", unit:"g"}, //this is what i want to filter with
{name:"other items here", quantity:"45", unit:"kg"},
{name:"example item", quantity:"74", unit:"l"},
]
},
{
name:"",
type:"",
items:[
{name:"tomatos", quantity:"14", unit:"kg"},
]
}
];
let UserInput = "tomato";
const res = stores.filter(({items}) => items.find(item => item.name.includes(UserInput)));
console.log(res);
.as-console-wrapper{min-height: 100%!important; top: 0}
let stores = [
{
name:"",
type:"",
items:[
{name:"tomato", quantity:"145", unit:"g"}, //this is what i want to filter with
{name:"other items here", quantity:"45", unit:"kg"},
{name:"example item", quantity:"74", unit:"l"},
]
}
]
let filterdStores = stores.filter(s=>s.items.some(i=>i.name==='tomato'));
console.log(JSON.stringify(filterdStores,null,2));
Use efficient Array.some

Get array from nested json value objects

I've been searching an answer for that but didn't found it.
I have an array like:
const data2 = [{
"abc":{
companyCity:"Cupertino",
conpanyName:"Apple"
}
},
{
"def":{
companyCity:"Mountain View",
conpanyName:"Google"
}
}
]
And I'd like to convert to and array like omiting the parent keys:
const data3 = [
{
companyCity:"Cupertino",
companyName:"Apple",
},
{
companyCity:"Mountain View",
companyName:"Google"
}
]
Perhaps, libraries like lodash have a method to achieve that, but didn't find it. Any help would be very appreciated :)
Iterate the array with Array.flatMap() (or lodash's _.flatMap()), and get the an the inner object of each item using Object.values() (or _.values()):
const data = [{"abc":{"companyCity":"Cupertino","conpanyName":"Apple"}},{"def":{"companyCity":"Mountain View","conpanyName":"Google"}}]
const result = data.flatMap(Object.values)
console.log(result)

How to merge object inside object [duplicate]

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 4 years ago.
I have an array
var input = [["group1","group2","group3" ], ["group1", "group5" ]]
I would like to merge two objects like this :
["group1","group2","group3", "group1", "group5" ]
I tried to merge two objects in one array, however, I couldn't get the answer.
Any help would be appreciated.
I'm not too familiar with js, but can't you concat two arrays with something like
var merged = input[0].concat(input[1]);
You can use concat() like so:
const input = [
["group1", "group2", "group3"],
["group1", "group5"]
];
const output = [].concat.apply([], input);
console.log(output);
Or alternatively, Array.prototype.flat():
const input = [
["group1", "group2", "group3"],
["group1", "group5"]
];
const output = input.flat(1);
console.log(output);
Or if that is "hard" data, and will not change, you could use an even simpler concat() operation:
const input = [
["group1", "group2", "group3"],
["group1", "group5"]
];
const output = input[0].concat(input[1]);
console.log(output);
You can use the concat function to combine the arrays.
const resultArr = [];
input.forEach(curr => {
resultArr.concat(curr);
});
You're talking about 'flattening the array'...
const flatten = (array) => {
return array.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
console.log(flatten([[1,2,[3]],4]));
ES5
array.reduce(function(a, x) { return a.concat(x); }, []);
ES6
array.reduce((a, x) => a.concat(x), []);
There is multiple approaches that you could take, my favorite would be to use the reduce method to transform your bi-dimensional array into one flat array and it would look like this :
function reducer(final_flat_array, inputItem) {
return [...final_flat_array, ...inputItem]
};
let flat_array = input.reduce(reducer, []);
or a more 'imperative' way I guess :
let flat_array = [];
input.forEach(item => flat_array.push(item);

Categories

Resources