Javascript object filtering - javascript

I have a list of products as an array of object, something like
[ {
id: 1,
price: 10,
name: 'product',
categories: [
{id: 1, name: 'category 1'} ]
},
{
id: 2,
price: 10,
name: 'product3',
categories: [
{id: 1, name: 'category 1'},
{id: 2, name: 'category 2'},]
},
...
]
And so on.
I'm trying to filter the product based on the category id, which is the best (and most modern) approach?, also since I'm working with Node.js, can it be better to work on a "copy" of the data, so that I always keep the full dataset intact for other uses? (like another filtering, or filter remove)

I'd use filter to apply a condition on each object. In that condition, I'd use some on the categories in order to find a product with at least one category that matches the condition:
const searchCategory = 1; // Just an exmaple
const result = products.filter(p => p.categories.some(c => c.id === searchCategory));

I would use .filter(), and in the callback, I'd use .some() to check if any of the categories have the correct id. If you only need one, you can use .find() instead of .filter().
Since you're working with object references, you have to be careful since the objects in the filtered array point to the same objects as the original array. In other words, if you modify the first element of the filtered array, the original array will update.
As for your question of whether you need to keep the full dataset, the way you phrased it is too broad to properly answer. You obviously should keep all the data somewhere, but at which level you use a filtered array and which level the full array is up to your architectural decisions.

Use Array.filter()
const arr = [ {
id: 1,
price: 10,
name: 'product',
categories: [
{id: 1, name: 'category 1'} ]
},
{
id: 2,
price: 10,
name: 'product3',
categories: [
{id: 1, name: 'category 1'},
{id: 2, name: 'category 2'},]
}
]
arr.filter(_o => _o.categories.filter(_c => _c.id === 2).length) // Change the "2" to whatereve you like to match the category ID

Related

Iterate array objects in js

I have an array objects
it looks like
\[
{id: 1, name: 'first', properties: \[{id: 1, name: 'propName1'}, {id: 2, name: 'propName2'}\]},
{id: 2, name: 'second', properties: \[{id: 1, name: 'propName1'}, {id: 2, name: 'propName2'}\]},
{id: 3, name: 'third', properties: \[{id: 1, name: 'propName1'}, {id: 2, name: 'propName2'}\]},
\]
I want to display first name of object for example 'first' and then I want to display names of properties objects propName1, propName2
so I want to see
first
propName1
propName2
second
propName1
propName2
third
propName1
propName2
Could you help me, guys?
I tried
{filters.map((filter) => {
let propss = ArrayFrom(filter.properties);
propss.map((prop) => (
<div>{prop.displayName}</div>
))
return(
<div className={style.title}>{filter.displayName}</div>
)
filter.properties.map((prop) => {
return (
<>
<div className={style.title}>{filter.displayName}</div>
<div>{prop.displayName}</div>
</>
);
});
})}
and I tried to save array via reduce, but without any result
First of all, you should not name yout array 'filter' since this can be confused with the Array.prototype.filter method ;)
Then you have an array of objects containing arrays, so you should iterate at the two level (in case your real structure actually gots more depth, you probably need to take a recursive approach).
considering your entry point :
const data = [
{
id: 1,
name: 'first',
properties: [
{id: 1, name: 'propName1'},
{id: 2, name: 'propName2'}
]
}, {
id: 2,
name: 'second',
properties: [
{id: 1, name: 'propName1'},
{id: 2, name: 'propName2'}
]
}, {
id: 3,
name: 'third',
properties: [
{id: 1, name: 'propName1'},
{id: 2, name: 'propName2'}
]
},
]
the two iterations couls look like somthing like that :
return data.map(entry => (
<>
<div className={style.title}>{entry.name}</div>
{entry.properties.map(prop => (
<div>{prop.name}</div>
))}
<>
))

best way to merge 2 disparate data sets in javascript? [duplicate]

This question already has answers here:
Merge two array of objects based on a key
(23 answers)
Closed 1 year ago.
What's the best way to merge 2 disparate data sets in javascript? For example,
const parentRecords = [{
id: 1,
mycol1: 'parent name',
}]
const childRecords = [{
childid: 2,
parentId: 1,
mycol2: 'child name',
}]
const mergedRecords = [...parentRecords, ...childRecords]
This code returns an array where each of the records above exist as separate rows. I need the result to look like this:
[{
id: 1,
mycol1: 'parent name',
childid: 2,
parentId: 1,
mycol2: 'child name',
}]
You didn't specify on which criteria items should be merged. In my answer I'm assuming it's based on the parent id and the children parentId:
const parentRecords = [{
id: 1,
mycol1: 'parent name',
}];
const childRecords = [{
childid: 2,
parentId: 1,
mycol2: 'child name',
}];
const result = parentRecords.map((x) =>
Object.assign(
x,
childRecords.find((y) => y.parentId === x.id)
)
);
console.log(result);

Inserting a unique id into a multidimensional object

I have an object with this structure (imagine it could be way bigger than this)
And I need to insert a new item inside, say, 'Name 3' children array. How would I go about creating a unique id for it? I have thought about saving the ids inside the object in a separate array and then creating one that is not on that, but I'd have to maintain it and I'm not sure that would be the best approach?
let obj = {
id: 1,
name: 'Name 1',
parent_id: null,
children: [{
id: 2,
name: 'Name 2',
parent_id: 1,
children: []
},
{
id: 3,
name: 'Name 3',
parent_id: 1,
children: [{
id: 4,
name: 'Name 4',
parent_id: 3,
children: []
}]
}
]
};
EDIT: The need for a unique id is for me to be able to delete an item. This is the code I've been given to work with, I can't alter the structure.

Generic way to map one type of nested array of object to another type of nested array of object

I have one source array let's say.
[{ id: 1
name: 'one'
...other-properties
children: [{
id: 1.1,
name: 'one.one',
...other-properties
children: [ upto n levels... ]
}]
}]
and I have one destination array, let's say.
[{ value: 1
label: 'one'
...other-properties
childs: [{
value: 1.1,
label: 'one.one',
...other-properties
childs: [ upto n levels... ]
}]
}]
in above source and destination names can be any. and keys can be of any number. so is there possibility to create generic function which can map source data to destination data?
const map = ({ id, name, ...rest, children }) => ({ value: id, label: name, ...rest, childs: children.map(map), });
You can use object destructuring and recursion to map one version to the other.

How can i check for a specific object (data) in an array?

I am quite a beginner when it comes to programming and currently having a Problem. I have an Array with 4 items (you can see the Array at the Code section below) and all the four items have their specific id (1-4).
The Thing i want to Program is a method which runs individual Code for each Array item. I thought i can solve this Problem by making if Statements where i simply check for the id's (which are individual at every item). But how can i do that??
If someone has a even better idea he can tell me that id for sure.
best regards John.
{ id: 1, name: 'BMW', price: 250, quantity: ''},
{ id: 2, name: 'Google', price: 110, quantity: ''},
{ id: 3, name: 'Apple', price: 1000, quantity: ''},
{ id: 4, name: 'Twitter', price: 50, quantity: ''}
You can achieve this with if statement. There are different approaches for this, but the basic approach will remain same. Loop over each element in the array and then check for ids. You can use the traditional for loop or you can use methods like some, filter etc.
You can simply iterate your array using simple for loop and check if id is equal to given id then return the whole object. in case of id is not matched it will return undefined. Consider the following code snippet:
let array = [{ id: 1, name: 'BMW', price: 250, quantity: ''},
{ id: 2, name: 'Google', price: 110, quantity: ''},
{ id: 3, name: 'Apple', price: 1000, quantity: ''},
{ id: 4, name: 'Twitter', price: 50, quantity: ''}];
function getValue(id)
{
for( var index=0;index<array.length;index++){
if( array[index].id === id){
return array[index];
}
};
}
console.log(getValue(1));
console.log(getValue(5));
From what I understand, you want to run separate pieces of code for different items in the array. If the elements of the array are fixed i.e they don't change, then you may write the different pieces of code for each item as function and add it as property to the corresponding item.
See the example below:
let BMWFunction = function(){
console.log('BMW!');
}
let googleFunction = function(){
console.log('Google!');
}
let myArray = [
{ id: 1, name: 'BMW', price: 250, quantity: '', code: BMWFunction},
{ id: 2, name: 'Google', price: 110, quantity: '', code: googleFunction }
]
for (let i = 0; i < myArray.length; i++){
myArray[i].code();
}
then for each item you loop through in the array, you can call the associated code attribute.
Loop through and compare the id of each item with the desired text using filter() - note that I can then either return the associuated object (for example - if you want to display the name) - or a text string if its not present.
You could also add logic in there to ensure that the id's are unique - ie if more than one result is found for a give n id - then you need to edit the id of the duplicates.
let items = [
{ id: 1, name: 'BMW', price: 250, quantity: ''},
{ id: 2, name: 'Google', price: 110, quantity: ''},
{ id: 3, name: 'Apple', price: 1000, quantity: ''},
{ id: 4, name: 'Twitter', price: 50, quantity: ''}
]
function findItem(id){
var foundItem = items.filter(function(item){
return(item.id == id)
});
if(foundItem.length > 0) {
return foundItem[0];
} else {
return "Item not found";
}
}
console.log(findItem('1')); // returns the object of the BMW
console.log(findItem('6')); // returns "Item not found"

Categories