How to compare each element in array to one single value? [duplicate] - javascript

This question already has answers here:
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Closed 4 years ago.
I have an array with multiple objects inside.
It's structured like that:
const Instructor = [
{ ID: '141',
InstructorNameAR: 'test',
InstructorNameEN: 'Mohamed Ahmed',
InstructorBriefAR: 'phd in chemistry',
InstructorBriefEN: 'phd in chemistry' },
{ ID: '140',
InstructorNameAR: 'test',
InstructorNameEN: 'Mahmoud Ahmed',
InstructorBriefAR: 'phd in chemistry',
InstructorBriefEN: 'phd in chemistry' },
]
I wanted to add other objects but filtered of duplicates based on their ID values.
Example of objects i want to add :-
const InstructorInstance = {
ID: 'ID',
InstructorNameAR: 'NAMEAR',
InstructorNameEN: 'NAMEEN',
InstructorBriefAR: 'BRIEFAR',
InstructorBriefEN : 'BRIEFEN'
}
I used this method to filter by ID.
But it didn't work as it compares only a single value of the array to the value i provided. which means it might be a duplicated object but still gets added because it did not check if it exists in each array element
Instructor.forEach(instance =>{
if(instance.ID !== InstructorInstance.ID){
Instructor.push(InstructorInstance);
}else{
console.log('Duplicate')
}
})

You have to loop the whole array first before deciding whether there is a duplicate or not. You can use forEach for that but every or some seem like the perfect fit for this kind of job:
const test = Instructor.every(instance => instance.ID !== InstructorInstance.ID);
if(test) {
Instructor.push(InstructorInstance);
}
Which means if every object in Instructor has a different ID than InstructorInstance, then push InstructorInstance into Instructor.
Note: You can put the test directly inside if without having to store it in a variable test:
if(Instructor.every(instance => instance.ID !== InstructorInstance.ID)) {
Instructor.push(InstructorInstance);
}
But that doesn't look, does it?

You can use some to check if that object already exists, if not, add it:
if (!Instructor.some(i => i.ID == instance.ID)) {
Instructor.push(instance);
}

Related

How do i access an element of an object that is inside an array and that array is inside an object [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed last year.
I need a small Help in JS? i want to access mail_address of this nested object, how will I do it
const data =
{ members:
[ { id : '7d8c03e88a8386f6453340c1db56'
, mail_address : 'trial.om'
, uniqsl : 'c6cce01'
} ] }
const data = {
members: [
{
id: '7d8c03e88a8386f6453340c1db56',
mail_address: 'trial.om',
uniqsl: 'c6cce01',
}
]
}
console.log(data.members[0].mail_address) // Prints "trail.om"
members is a array of objects, but it has one single element. You access this element at the index 0.

How to get data and create an array from an object when keys are same in javascript? [duplicate]

This question already has answers here:
Javascript object literal - possible to add duplicate keys?
(3 answers)
Closed 1 year ago.
This is the scenario I am talking about:
let obj = {
id: "kjhgfr^&*()(*UY",
id: "kjhgfr^OIJHB",
id: "kjhgfr^)(*&^%Y",
id: "DFGHI(*&YTRDTYHKI*",
id: ")(IUHGVYUJKO))(*UY",
id: "VGYUKO(*UYH",
id: "BHYUIOP)(*&^T%",
id: "0987654567890",
id: "5678909876543",
};
I want to create an array with ids like this.
[
"5678909876543",
"0987654567890",
"VGYUKO(*UYH",
"kjhgfr^&*()(*UY",
"VGYUKO(*UYH",
];
Your object is incorrect.
Possible it is the same as:
Javascript object literal - possible to add duplicate keys?
As a result, it will be override to get the last value.
let obj ={id:"kjhgfr^&*()(*UY",id:"kjhgfr^OIJHB",id:"kjhgfr^)(*&^%Y",id:"DFGHI(*&YTRDTYHKI*",id:")(IUHGVYUJKO))(*UY",id:"VGYUKO(*UYH",id:"BHYUIOP)(*&^T%",id:"0987654567890",id:"5678909876543",};
console.log(obj);
// { "id": "5678909876543"}
You cannot have duplicate keys. Each identical key will overwrite the previously defined value.
You could try this instead (assuming you have control over the input):
let obj = {
id: ["kjhgfr^&*()(*UY",
"kjhgfr^OIJHB",
"kjhgfr^)(*&^%Y",
"DFGHI(*&YTRDTYHKI*",
")(IUHGVYUJKO))(*UY",
"VGYUKO(*UYH",
"BHYUIOP)(*&^T%",
"0987654567890",
"5678909876543"]
};
This is similar to the following question: Read and loop through an object with non-unique key value pairs

How do I exclude a list of keys when cloning a JavaScript object? [duplicate]

This question already has answers here:
JavaScript: filter() for Objects
(19 answers)
Closed 2 years ago.
I am working on an app with a normalized state in Redux. One of my entities is the 'parent' entity of another, so when I delete that parent entity I want to delete all of the children entities associated with that parent.
For deleting a single entity (1 ID), I have been using this pattern:
// ../reducers/entity.js
case DELETE_ENTITY: {
const entityId = action.payload.entityId;
const {[entityId]: ignore, ...stateWithoutEntity} = state;
return stateWithoutEntity;
}
For context, the state in the above snippet is shaped as such:
{
ID_1: {
//entity 1 value
},
ID_2: {
//entity 2 value
},
// etc...
}
Is there a similar patten for deleting a list of multiple entities (n IDs)?
In other words, is there a pattern for cloning a JavaScript object while excluding several keys?
// ../reducers/entity.js
case DELETE_PARENT_ENTITY: {
const parentId = action.payload.parentId;
const childrenIdsToRemove = action.payload.children;
// How do I clone the state while excluding each ID in childrenIdsToRemove?
}
If you have lots of keys of an object you want to remove, you can use Object.entries and then filter, and then finally reduce to make the final object.
Below is a simple example, that basically remove all keys that start with entity.
Update, Thanks to comments changed to fromEntries instead of reduce
const x = {
'entity1': 1,
'something': 2,
'entity2': 3,
'another': 4
}
const y =
Object.fromEntries(Object.entries(x)
.filter(([k]) => !/^entity/.test(k)));
console.log(y);

How to access a dictionary inside a dictionary? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
I'm trying to figure out how to access the value inside two dictionaries via JavaScript.
The JSON output from the server is;
{"meta":{},"linked":{custom_fields":[{"id":"4","name":"Department"}],"custom_field_values":[{"id":"0001","value":"Marketing","links":{"custom_field":{"id":"4","type":"custom_fields"}}}]
I need to list Marketing as the department. I can't seem to access "links" to pull the id.
If I create var linked = linked.custom_field_values; I get a response.
{"id":"0001","value":"Marketing","links":{"custom_field":{"id":"4","type":"custom_fields"}}}
As soon as I try to var cfl = linked.links.custom_field.id it's saying links isn't defined. So I'm not sure what I'm doing wrong in trying to create a variable for this?
Links is a dict with Custom_field right under as a dict with the values I need.
Wouldn't this print out the department correctly if everything works right?
if(cfl.id == 4){
console.log('Department is ' + linked.value);
}
It looks like custom_field_values an array. You have to look at the first item in the array like so var linked = linked.custom_field_values[0];
With a proper formatted object, you see, that you have an array inside. So you need to take an index for the array.
var object = {
meta: {},
linked: {
custom_fields: [
{
id: "4",
name: "Department"
}
],
custom_field_values: [
{
id: "0001",
value: "Marketing",
links: {
custom_field: {
id: "4",
type: "custom_fields"
}
}
}
]
}
};
console.log(object.linked.custom_fields[0].id);
console.log(object.linked.custom_field_values[0].id);

Angular2 Typescript how to retrieve an array from inside an object [duplicate]

This question already has answers here:
Find a value in an array of objects in Javascript [duplicate]
(20 answers)
Closed 5 years ago.
When I do console.log of the following:
console.log(this.categories);
I get this structure:
which was created from this json from the api:
[
{
"id":"dff0bb3e-889f-43e6-b955-52cc7203952f",
"name":"Wood",
"category_types":[
{
"id":"49b31f43-d98d-43c8-9798-088ec6914fe5",
"name":"Solid"
},
{
"id":"8592716a-ffd5-4e97-ba9e-6a64ba6e48f1",
"name":"Engineered"
}
]
},
{
"id":"6b2b6914-6c64-4389-a327-be3f08fd066d",
"name":"Carpet",
"category_types":[
{
"id":"0e2c8473-90fb-4806-a6e7-2389eeb0f9e4",
"name":"Loop pile"
},
{
"id":"3c762653-4f0d-42d2-a84e-133c7051c95b",
"name":"Cut pile"
},
{
"id":"0997d4dc-e886-46ef-83b4-d90c4fb72553",
"name":"Cut \u0026 loop pile"
}
]
}
]
Given that I have the value 'Wood' in a string variable called value, how do I get hold of the category_types array for the Wood object?
console.log(this.categories[value]);
returns undefined.
You want to find object that has name of 'Wood', then get category_types. Array.prototype.find returns first value that meets the condition in the provided test function. In your case, it could look like this:
this.categories.find(value => value.name === 'Wood').category_types
You can use Array.filter:
let wood = this.categories.filter(category => {
return category.name === "Wood";
})[0];
This will filter your categories to retrieve the ones with name wood, then you take the first one. If you didn't find anything with name === "Wood" in your array, then it will be undefined.

Categories