How do I update selected values in react multiselect - javascript

I have a modal in which I edit my model. In my form, I also have a multi-select tag field. The "tags" is an array of objects with labels and values as show below.
There is a dummy tags object (mimicking a database) which all the tags are selected from.
const dummyTags = [
{ label: "Test 1", value: "Test 1" },
{ label: "Test 2", value: "Test 2" },
{ label: "Test 3", value: "Test 3" },
];
So, if I selected "Test 1" and "Test 2", my tags array becomes (only the values are then saved in the database):
const tgs = [
{
label: "Test 1",
value: "Test 1"
},
{
label: "Test 2",
value: "Test 2"
}
];
However, during update, the tags come from the database as ['Test 1','Test 2'].
I want to use the tags from the database shown in the line above to compare the dummyTags array so I can have a new array of objects with values like the tgs array above.
At the moment, this is what I am doing:
let newtags = [];
if (groupTags.length > 0) { //groupTags is the tags from the database
groupTags?.forEach((tag) => {
newtags.push({ label: tag, value: tag });
});
}
This works, but I think it's not reliable. What if the label and value are not the same for a particular tag?
Is there a better way of implementing this?

const arr = ['Test 1','Test 2', 'Test 3']
const result = arr.map(d => ({label: d, value: d}));
console.log(result)

Related

Returning the ids from the object within the arrays

I have a multidimensional javascript array of objects that I am trying to use to simply collate the Unit id into a new array as shown below.
What is the best solution for returning the id within the inner value so I just get an array of the ids whatever I try seems to not work
[
{
units: [
{
id: 10000282,
name: "Group 1",
},
{
id: 10000340,
name: "Group 2",
},
{
id: 10000341,
name: "Group 3",
},
],
},
{
units: [
{
id: 10000334,
name: "Group 4",
},
],
},
]
Expected output - just return an array with simply the ids
e.g
ids = [ 10000282, 10000340, 10000341, 10000334 ]
Assuming that data is in variable data:
> data.map(o => o.units.map(u => u.id)).flat()
[ 10000282, 10000340, 10000341, 10000334 ]
This assumes you're in an environment where .flat() is a thing.
If that's not the case, the longer way around is
const ids = [];
data.forEach(o => {
o.units.forEach(u => {
ids.push(u.id);
});
});

Inserting array item into JS object

I have a unique situation that I'm struggling with. I have some data like this. Excuse any incorrect terms as I'm fairly new to this.
usersByName: {
"tester": {
0: {
id: 123
name: "Some Name"
data: "Some data"
},
1: {
id: 124
name: "Some Name 2"
data: "Some data 2"
},
2: {
id: 125
name: "Some Name 3"
data: "Some data 4"
},
},
"tester 2": {
0: {
id: 12
name: "Some Name"
data: "Some data"
},
1: {
id: 13
name: "Some Name 2"
data: "Some data 2"
},
}
}
I am returning a piece of data like this.
{
id: 44
name: "Some Name New"
data: "Some data New"
}
and a name like tester 2.
How can I add the new piece of data to the name I have found so the new data gets added as a third element to tester 2.
I am using react and next js so hoping to add it directly to the state if possible.
I think something like this but can't work out the obvious parts of it that are wrong
this.setState((prevState) => ({
usersByName: { // copy all other key-value pairs
newuservar: {
...prevState.usersByName.newuservar, // copy all pizza key-value pairs
X: newData,
},
},
}))
Since I see the user objects have the key start with numbers, I assume they're arrays. Try this:
// newuservar = 'tester 2';
this.setState((prevState) => ({
usersByName: {
...prevState.usersByName,
[newuservar]: prevState.usersByName[newuservar].concat(newData)
},
}))

how to use filter method in array and print only specific value of the object

const arr = [
{ value: "Value one",
label: "Value at one"
},
{
value: "Value 2",
label: "Value at 2"
},
{
value: "" ,
label: "Value at 3"
}
]
This is my array, which I am passing as a props in different component. But i want to add the filter also, that if the value in array is empty, then do not show its label in child component
{arr.filter(val => !val.value).map((data)=>
<ChildComponent data ={data}/>
)}
My doubt is how to use .filter to hide the empty values. I have written the logic but its not working even when there is a value in an array.
when i m doing console.logs to get the value of array:
console.logs(this.arr), output is as follows:
1: Object { value: "Value one", label: "Value at one" }
2: Object { value: "Value 2", label: "Value at 2" }
3: Object { value: "", label: "Value at 3" }
I want only to get the values of object 1, not sure how to get it. console.log("sampleData", arr.map(data=>data.label)) gives output as: [ "Value at one", "Value at 2", "Value at 3" ] . Though i want the output as only ["Value at one"].
Can anyone help me with how to filter the values that exist and print only the 1st value/second value/third value separately from the array.
Your code is right the only thing you need to change it arr.filter(val => !val.value) tbhat should be arr.filter(val => val.value != '') or arr.filter(val => val.value) and if you want to valid white spaces you have do a arr.filter(val => val.value.trim() != ''); also the console.log() is showing you the first array, so If you want to get the new value you have to create a new variable assigning that value like let newarray = arr.filter(val => val.value) and if you console.log(newarray) it would display the right values.

How to Sort an Array of Objects containing References to Other Objects that Should Come First?

How can I sort an array of objects containing references to other objects in the same array that should come first?
I have an array of objects that need to be sorted by two factors:
An object should come after all of its "members" ("members" are references to the "name" of other objects in the same array).
Then, where it could not be sorted by the criteria above, it should be sorted in alphabetical order by "name".
For example, consider the following MVCE:
const example = [
// This object named "Example 1" should come after its members ("Example 4"):
{
name: 'Example 1',
members: [
'Example 4',
],
},
// This object named "Example 2" should come after its members ("Example 1" and "Example 3"):
{
name: 'Example 2',
members: [
'Example 1',
'Example 3',
],
},
// This object named "Example 3" does not have any members, so it does not necessarily need to change position:
{
name: 'Example 3',
members: [],
},
// This object named "Example 4" does not have any members, so it does not necessarily need to change position:
{
name: 'Example 4',
members: [],
},
// This object named "Example 5" should come after its members ("Example 1"):
{
name: 'Example 5',
members: [
'Example 1',
],
},
];
// The objects in "example" should also be sorted by "name" ASC, where it can not be sorted by "members".
example.sort((a, b) => {
if (a.members.includes(b.name) && b.members.includes(a.name)) {
// Circular Reference: Skip because "a" AND "b" cannot be members of each other at the same time, so no re-ordering needed at the moment:
return 0;
} else if (a.members.includes(b.name) && !b.members.includes(a.name)) {
// "a" includes "b" as a member, so "a" should come after "b":
return 1;
} else if (!a.members.includes(b.name) && b.members.includes(a.name)) {
// "b" includes "a" as a member, so "b" should come after "a":
return -1;
} else if (!a.members.includes(b.name) && !b.members.includes(a.name)) {
// Neither "a" nor "b" include each other as a member, so no re-ordering needed at the moment:
return 0;
} else {
// OTHERWISE, use the secondary sort by "name", where it could not be sorted by "members":
return a.name.localeCompare(b.name);
}
});
console.log(example);
The code above produces an incorrect result:
"Example 1"
"Example 3"
"Example 2"
"Example 4"
"Example 5"
The correct, intended result should be:
"Example 3"
"Example 4"
"Example 1"
"Example 2"
"Example 5"
What's the best way to sort this array based on the criteria I have listed above?

MongooseJS trying to populate using nested query operator

I have a code:
const profiles = await Profile.find({ profileVisibility: true })
.populate("products", null, {
itemName: "Item 1"
});
This works because I am trying to find itemName which is direct field of the Profile.
However, in the same Profile Schema I have nested object named lists which is a object with nested fields example:
ProfileSchema = {
itemName: "Item 1",
lists: {
name: "name 1",
price: "price 1"
}
}
When I try to do this I get null (this happens every time I try to query nested properties):
.populate("list", null, {
lists: {name: { $eq: 'name 1' } }
}

Categories

Resources