Removing object with property in array leaves an empty object - javascript

I'm trying to remove an item with a property from array object based on the key but it is leaving an empty object. For example,
var items = [{"fruits": ["Apple","Banana"]},{"veggies": ["Potato","Carrot"]}]
So I want to remove the item with the fruits property. This is the code I tried...
var filter = items.map(({ fruits, ...rest }) => rest);
This gave me an output of
[{},{"veggies": ["Potato", "Carrot"]}]
Why is it leaving a trace of an empty object? And how to get rid of that empty object?

Please use filter function.
var items = [{"fruits": ["Apple","Banana"]},{"veggies": ["Potato","Carrot"]}];
const result = items.filter(val => !val.hasOwnProperty("fruits"));
console.log(result);

Try this
var items = [{"fruits": ["Apple","Banana"]},{"veggies": ["Potato","Carrot"]}]
console.log(items.filter(item => !item.hasOwnProperty('fruits')))

.map will return an array of the same length, mapped to a new array. To remove entries use .filter:
var items = [{"fruits": ["Apple","Banana"]},{"veggies": ["Potato","Carrot"]}]
var filter = items.filter(i => !i.fruits);
console.log(filter);

Related

How to check if values in array is present in object key of object array

I want to check if values in one array is present in object key of object array.
For example: arr = ["id1", "id2"]
objectArr = [{id: "id1"}]
I want to throw not found error in this case when id2 is not present in id of object array.
Help of any kind would be appreciated!
You can use filter and some for that:
var objectArr = [{id: "id1"}, {id: "id3"}]
var arr1 = ["id1", "id2"];
const notFounds = arr1.filter(el => !objectArr.some(obj => obj.id === el ));
console.log(notFounds); // ["id2"]
JS Array some:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
JS Array filter:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
If You iterate over objectArr, You can get object fields in form of array with: Object.entries(your_object).
for (const obj of objectArr) {
for (const item of Object.entries(obj)) {
// where item is field in object
// now You can compare if item is in [id1,id2]
}
}
You can try something like this
var arr = ["id1", "id2", "id3", "id4"];
var n = arr.includes("id2"); //true
For an array of objects. If the id is unique in the array
var arr = [{id:"id1"},{id:"id2"},{id:"id3"},{id:"id4"}]
const found = arr.some(el => el.id === "id3") // true
EDIT: ran.t has a better answer that keeps track of which ids are not found.
It sounds like what you're looking for is .every() method. Which will allow you can check each element in the array passes a given condition.
You can combine this with the .some() method to check at least one object in the objectArr has id equal to your element
const allElementsFound = ["id1", "id2"].every(el => objectArr.some(obj => obj.id === el))
if(!allElementsFound) {
// throw error
}

Return only value of listed index from an array JavaScript

I'm trying to filter an array based on the listed index in another array.
For example:
const item = ['apple','orange','watermelon','pineapple'];
const index = [1,3];
Based on the index array , I want to return an array of [ 'orange','pineapple']
How do I do that in an efficient way? I tried using comparison between 2 array , but i think it is not very good for efficiency.
You can do map over the index array and just do a regular indexing to look up the item from the item array.
const result = index.map(idx => item[idx]);
No need for comparisons when you already have the indices. You just access them directly instead.
You can do something like this:
const filteredArray = index.map(i => item[i]);
Output:
You can do the following,
const res = [];
item.forEach((item, idx) => { if(index.includes(idx)) res.push(item); });
console.log(res);

What is wrong in the following comparing and object property implementation it returns just 2 value (JS)?

I am trying to check if the first array includes the object that has the same id as the first element in the second array. Then for that object in the first array add the following 2 property values.
I tried the following but it returns only an array of that new values instead of returning the full first array of objects that includes that modified object with new properties.
products = products
.filter(item => item.id === productsByTags[0].id)
.map(item => (item.tags = 'shoes'), (item.keywords = 'black'))
How can I get the full array of objects where those 2 new properties, values are added to that object which has the same id based on above condition?
You need to return a new objectby spreading the actual object and two new properties.
.map(item => ({ ...item, tags: 'shoes', keywords: 'black' }))
The problem you are running into is that both .filter and .map return new arrays. So once you have filtered, you have already removed all items that do not match your check. If you move it all into a single map, you can mutate only the items that you want to while still returning the none mutated items as well.
products = products.map(item => {
let newItem = {...item};
if(item.id === productsByTags[0].id){
newItem.tags = 'shoes';
newItem.keywords = 'black';
}
return newItem;
})
products = products
.filter(item => item.id === productsByTags[0].id)
.map(item => {
item.tags = 'shoes';
item.keywords = 'black';
return item;
});
Post filtering the data you were trying to add the new properties to object so you should return the object to map to return you array of objects.

How to update object property which is an array?

I am working in a ReactJS project and have a filterGroupsData property in my state. This is an array of objects, each object has a filters property which is an array of string values. See below:
filterGroupsData:[
{"key":1532957059388,"id":1532957059388,"filters":[]},
{"key":1532957059612,"id":1532957059612,"filters":[]},
{"key":1532957059847,"id":1532957059847,"filters":[]}
]
How can I add elements to the filters property of a object with a given id?
I attempted to this but this results in overwriting the whole object with on value:
// update the filter array of the object with id == activeId
let updatedFilterGroupsData = filterGroupsData.map(filterGroupData => filterGroupData.id === activeId ? filterGroupData.filters.push('test') : filterGroupData)
this.setState({filterGroupsData: updatedFilterGroupsData});
Appreciate any help.
You can use findIndex to get the index of the filter group you want to update, and then create a copy of the object and the filters array and add a new entry to it.
Example
const id = 1532957059388;
this.setState(previousState => {
const filterGroupsData = [...previousState.filterGroupsData];
const index = filterGroupsData.findIndex(group => group.id === id);
filterGroupsData[index] = {
...filterGroupsData[index],
filters: [...filterGroupsData[index].filters, "new filter"]
};
return { filterGroupsData };
});
Here: filterGroupData.filters = 'test'
You're setting the prop value to a string instead of putting in the array.
You need to push the item into the filters array like:
filterGroupData.filters.push('test');
filters is a array so you need to use push('test') with multi line code inside map:
var filterGroupsData = [
{"key":1532957059388,"id":1532957059388,"filters":[]},
{"key":1532957059612,"id":1532957059612,"filters":[]},
{"key":1532957059847,"id":1532957059847,"filters":[]}
]
var activeId = 1532957059612;
let updatedFilterGroupsData = filterGroupsData.map((filterGroupData) => {
if(filterGroupData.id === activeId) {
filterGroupData.filters.push('test');
}
return filterGroupData
});
console.log(updatedFilterGroupsData);

array.map() is not a function reactjs

I have a function which stores data after splicing from an array.
const removedItemstax = {};
function findAndRemove1(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
//Remove from array
var removedItem= array.splice(index, 1);
removedItemstax.push(removedItem);
}
});
}
When I try to get map it using below code to get distinct values const tax = removedItemstax.map(d => d.taxId) I'm getting an error that .map() is not a function.
But when I push the array removedItemstax to console I get to see all the elements stored within it.
I get the same error when I pass the array removedItemstax = {} via props after setting a state to it.
Mapping returns undefined, however pushing it directly displaying complete data assigned to the array. I am following the regular method to map.
You can try this way:
const removedItemstax = [];
function findAndRemove1(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
//Remove from array
var removedItem = array.splice(index, 1);
removedItemstax.push(removedItem);
}
});
}
Instead removedItemstax be a object, him can to be a array
I figured out the reason for getting undefined elements when mapping. This is due to a multidimensional array being stored in attribute const removeItemstax = [].
I'm using the below command to flatten the multidimensional array into a normal array before mapping it.
Here's the syntax:
const removedItemstax1 = [].concat.apply([], removedItemstax);

Categories

Resources