array.map() is not a function reactjs - javascript

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);

Related

Removing object with property in array leaves an empty object

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);

How to omit a particular key while pushing json objects to an array?

So, I have a JSON array of objects , which in turn contains other arrays of objects. This array of objects has no particular fixed structure as such so its very difficult for me do something like delete mainArray[0].obj.subobj[1].objToOmit;
So I have a key/object called possibleAnswers which I need to remove/omit. In my program I am pushing the contents of one array into another array. So while I am pushing the contents of first array of objects into another, I need to omit the possibleAnswers object from being pushed.
Is there any way or function that searches an array of objects and helps me omit the necessary key? Or what would be a solution as per your thoughts?
Example :
Here is a minimal example: https://codebeautify.org/jsonviewer/cb9fea0d
Edit: In the above JSON there is a key called possibleMembers which is wrong. its possibleAnswers
var collectObservationsFromConceptSets = function () {
$scope.consultation.observations = [];
_.each($scope.consultation.selectedObsTemplates, function (conceptSetSection) {
if (conceptSetSection.observations) {
_.each(conceptSetSection.observations, function (obs) {
$scope.consultation.observations.push(obs);
});
}
});
}
In the above code while pushing the object into another array, how can I omit the possibleAnswers keys? Is there a way to omit?
Thanks a lot people! Both the answers are correct and have generated the exact correct output. Unfortunately I can only select 1 answer as correct and its going to be random.
This is a recursive omit that uses _.transform() to iterate and ignore one or more keys in an array:
const omitRecursive = (keys, obj) => _.transform(obj, (acc, v, k) => {
// if key is view, and it and has an id value replace it with equivalent from views
if(keys.includes(k)) return;
acc[k] = _.isObject(v) ? omitRecursive(keys, v) : v;
});
const data = [{"observations":[{"possibleAnswers":[],"groupMembers":[{"possibleAnswers":[]},{"groupMembers":[{"possibleMembers":[]},{"possibleMembers":[]}]}]}]},{"observations":"Same as above"},{"observations":"Same as above"}];
const result = omitRecursive(['possibleAnswers'], data);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
This function will remove all 'possibleAnswers' if called on your original array like removeKey(arr, 'possibleAnswers')
function removeKey(objOrArr, keyToRemove) {
if (Array.isArray(objOrArr)) {
objOrArr.forEach(o => removeKey(o, keyToRemove));
} else if (typeof objOrArr === 'object') {
delete objOrArr[keyToRemove];
Object.values(objOrArr).forEach(v => removeKey(v, keyToRemove));
}
}

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);

Get property value from an object inside of an array

I'm trying to grab class code property value from the object inside each array belonging to "class". (I'm aware my data is convoluted).
This is my student array:
student = [
{"class":[{
"code":"PSJ001",
"professor":"McHale",
"description":"course description"}]
},
{"class":[{
"code":"ENG303",
"professor":"Dench",
"description":"course description"}]
},
{"class":[{
"code":"SCI003",
"professor":"Biju",
"description":"course description"}]
}
]
What I'm trying to get is...
['PSJ001','ENG303','SCI003']
This is what I have...
let classCodes = [];
for (const i in student) {
classCodes = classCodes.concat(student[i].map(obj => {
return obj.code;
}));
}
What am I doing wrong here? (written in jsx)
You can use map() to get desired result
var student = [{"class":[{"code":"PSJ001","professor":"McHale","description":"course description"}]},{"class":[{"code":"ENG303","professor":"Dench","description":"course description"}]},{"class":[{"code":"SCI003","professor":"Biju","description":"course description"}]}];
var result = student.map(function(e) {
return e.class[0].code;
});
console.log(result)
Basically this will work reliable:
student.map(o => o.class.map(c => c.code)).reduce((obj, arr) => arr.push(...obj) && arr, []);
First we use .map() to get the classes, and inside we use .map() again to get the codes. This gives us a array of arrays. Then we use .reduce() to flatten that array.

Transformation array to nested object

I try to convert some data into a javascript object. The data looks like this:
data = [["a","a","a","value1"],
["a","a","b","value2"],
["a","b","value3"],
["a","c","a","value4"]]
What I want to get is:
a = {
"a":{
"a":"value1",
"b":"value2"
},
"b":"value3",
"c":{
"a":"value4"
}
}
Since the amount of nested attributes varies I do not know how to do this transformation.
This should be the function you're looking for:
function addItemToObject(dict, path){
if (path.length == 2){
dict[path[0]] = path[1];
} else {
key = path.shift()
if (! dict[key]) {
dict[key] = {};
}
addItemToObject(dict[key], path);
}
return dict;
}
var result = data.reduce(addItemToObject,{});
The function addItemToObject is a recursive function which creates the depth and inserts the value.
This is applied to everything in data using reduce;
Here's a solution using Ramda.js
const data = [
["a","a","a","value1"],
["a","a","b","value2"],
["a","b","value3"],
["a","c","a","value4"]
]
const transformData =
R.pipe(
R.map(R.juxt([R.init, R.last])),
R.reduce(
(obj, [path, value]) =>
R.assocPath(path, value, obj),
{},
),
)
console.log(transformData(data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
I don't get your desired solution as there are 4 blocks of data but only 3 properties in the final object.
However, this is how you can iterate through an array and its child arrays:
var data = [["a","a","a","value1"],
["a","a","b","value2"],
["a","b","value3"],
["a","c","a","value4"]];
//Store your results in here
var result = {};
//Iterate each block of data in the initial array
data.forEach(function(block){
//block will refer to an array
//repeat with the child array
block.forEach(function(item){
//item will point to an actual item in the child array
});
});
forEach() will call a provided function on each item within an array.

Categories

Resources