This question already has answers here:
Remove array element based on object property
(12 answers)
Closed 8 years ago.
I have array like this
var curChanges = [
{id:1, isChecked:true},
{id:2, isChecked:false},
{id:3, isChecked:true}
];
Now, if i want to remove second array i.e {id:2, isChecked:false} dynamically, How do i do?
Here id is unique.
Thanks in advance.
Firstly, you have a syntax error. Object property values are set with :, not with =:
var curChanges = [
{
id: 1,
isChecked: true
},
// etc...
];
Assuming the order of elements in the array is not fixed, the easiest way to achieve what you're trying to do will be to use the ES5 Array.prototype.filter method:
curChanges.filter(function (elem) {
return elem.id !== 2;
});
If you return true from the filter function, the element will stay in the array. If you return false, it will be removed.
first off, invalid array. Should be : not =
so it becomes:
var curChanges = [ {id:1, isChecked:true}, {id:2, isChecked:false}, {id:3, isChecked:true}];
Use a filter to remove based on id:
curChanges.filter(function(i) { return i.id!=2;})
Or to directly remove the second element :
curChanges.splice(1,1);
Related
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 to remove an array from json array in react js. I tried something like this. but not working
Now the response is directly set to atate as follows
let { newData} = response;
please help to filter item. Either from response or from state variable
response.map((res, index) => {
if (res.status==1) {
res.splice(index, 1) // remove element
};
})
response is [object Object] when i alerted
[
{id:1, status:1},
{id:2, status:0},
{id:3, status:1},
]
Use filter instead of map and filter out the unwanted object/s.
const filteredArray = response.filter((res) => res.status !== 1);
Please just be aware that this will create a new array and not mutate your original array.
You should create a new one of Array, You can try..
let temp = []
response.forEach((res, index) => {
if (res.status !== 1) {
temp.push(res)
}
})
The better solution is to use the filter method, or if you still want to use the splice, It should be response.splice
Note: Using the splice approach is wrong as pointed out by #VLAZ, as it shifts the elements but the indexing by forEach will continue irrespective of the elements spliced off.
var response = [
{id:1, status:1},
{id:2, status:0},
{id:3, status:1},
]
response.forEach((res, index) => {
if (res.status==1) {
response.splice(index, 1) // remove element
};
})
console.log(response);
This question already has an answer here:
JS : Convert Array of Strings to Array of Objects
(1 answer)
Closed 3 years ago.
I am trying to add id in a components array. id's will be incrementing based on the no. of components.
component_names = ['test1', 'test2'];
I want to create a new array components which will become :
components = [{id:1, name: 'test1'}, {id:2, name: 'test2'}]
// The ids will increment as the no. of components increase.
What I am trying:
let arr=[];
for(let i=0;i<component_names.length;i++){
arr.push({id:i+1, name: component_names[i]});
}
The above solution works but can I do the same with any of the higher order functions in javascript?
A simple map will work, where parameter 1 is the item and parameter 2 is the index.
let component_names = ['test1', 'test2']
let result = component_names.map((itm, idx) => ({id:++idx,name:itm}))
console.log(result)
let arr = component_names.map((name, index) => ({ name: name, id: index + 1 }));
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);
}
This question have two parts: first, I want to create an array that works like a table. It will have two columns ids (Game-Id and Game-Name). I have been working in something like this:
var game_list =
[
{id:1, name:'Vampires hunter'},
{id:2, name:'Christmas vampires'},
{id:3, name:'Fruit hunter'},
{id:4, name:'The fruitis'},
{id:5, name:'james bond'},
{id:6, name:'Vampires hunter'},
{id:7, name:'Vampires avalon'},
{id:8, name:'Vampires warrior'},
{id:9, name:'Vampires hunter'},
{id:10, name:'Vampires hunter'},
];
But I'm not able to access elements in this kind of array / object, not even a document.write of an element.
What I need is to create a function that will search for a specific string inside that array. The function will have 2 parameters (the string and the array) and it will give us a result an array of the elements with game names and ids that match that string.
Use filter:
function filter(arr, string) {
return arr.filter(function (el) {
return el.name === string;
});
}
filter(game_list, 'Vampires avalon'); // [{ id=7, name="Vampires avalon"}]
Demo
If you want to be really clever, add some regex to match the string anywhere in the name:
function filter(arr, string) {
var regex = new RegExp('.*' + string + '.*');
return arr.filter(function (el) {
return regex.exec(el.name);
});
}
filter(game_list, 'hunter');
Which will give you this:
[{"id":1,"name":"Vampires hunter"},{"id":3,"name":"Fruit hunter"},{"id":6,"name":"Vampires hunter"},{"id":9,"name":"Vampires hunter"},{"id":10,"name":"Vampires hunter"}]
Demo
A simple loop and check will do:
function checkArray(name) {
var arr = [];
for (var i = 0; i < game_list.length; i++) {
if (game_list[i].name == name)
arr.push(game_list[i])
}
return arr;
}
Will compare the name passed in with the name of each object, and returns an array of matching objects. If you only want names containing the passed in string, use indexOf and check on -1