What is the best way to delete objects from Array - javascript

I am wondering if what is the best way to find all Indexes of objects in an Array and then delete them from the Array.
Currently, my code looks like as below;
var data = _.find(group.value, function(valueItem){ return valueItem.value == filter.value });
var index =_.indexOf(group.value,data);
group.value.splice(index,1);
This works great, but only gets me the first index if the index is more than once. So, I am looking for a method that will get me all indexes in my Array, so I can loop through in remove all

Use filter to create a new array of objects.
Based on your example this code creates new arrays based on the value (name) of each value property. I've wrapped the filter code in a function (getData) that you can call with the original array and the name you want to check as arguments.
If there is no match the function will return an empty array.
const arr = [
{ id: 1, value: 'bob' },
{ id: 2, value: 'dave' },
{ id: 3, value: 'bob' },
{ id: 4, value: 'bob' }
];
function getData(arr, name) {
return arr.filter(obj => obj.value === name);
}
console.log(getData(arr, 'bob'));
console.log(getData(arr, 'dave'));
console.log(getData(arr, 'mary'));

Related

how to update the array object using id and the props in javascript

I have an array object and I want to update the array object using id and props.
below is the structure of array object,
array object = [{columGrp:"All",deafultColumnName:"a",id:0},{columGrp:"ll",deafultColumnName:"ww",id:1},{columGrp:"oo",deafultColumnName:"qq",id:2},{columGrp:"qq",deafultColumnName:"ee",id:3}]
I have an editable table design and when a field changes I am passing field name, id, and changed value. based on that how can I update the object array.
const onChange=(props,value,id)=>{
//code here
}
onChange("columGrp","qwerty",1);
// result =>
array object = [{columGrp:"All",deafultColumnName:"a",id:0},{columGrp:"qwerty",deafultColumnName:"ww",id:1},{columGrp:"oo",deafultColumnName:"qq",id:2},{columGrp:"qq",deafultColumnName:"ee",id:3}]
a help would be really appreciable.
You can find the object by id from your array of objects using the filter function. If the object exists, you then change the given property, passing the given value. Objects work by reference in javascript so any changes in the found object will affect your object inside your array too.
const objectsArray = [{
columGrp: "All",
deafultColumnName: "a",
id: 0
}, {
columGrp: "ll",
deafultColumnName: "ww",
id: 1
}, {
columGrp: "oo",
deafultColumnName: "qq",
id: 2
}, {
columGrp: "qq",
deafultColumnName: "ee",
id: 3
}];
const onChange = (props, value, id) => {
const obj = objectsArray.find(x => x.id === id);
if (obj) {
obj[props] = value;
}
}
onChange("columGrp", "qwerty", 1);
console.log(objectsArray)

Get key name of a javascript object in an array of objects

I have some Entries, those entries have a Category assigned to them, and each entry has a numeric Value;
{
category: "cat1",
value: -100
}
This is my entry ^. I run a Loadash GroupBy to group all the categories.
const groups = _.groupBy(dataSource, (entry) => entry.category);
This snippet here returns like this:
{
"cat1": [
{
category: "cat1",
value: -100
},
{
category: "cat1",
value: +10
},
],
"cat2": [
{
category: "cat2",
value: -100
},
{
category: "cat2",
value: +40
},
//and so on...
}
The keys are the Category names. The objects are the related entries.
I need to run a consecutive Map with an embedded Reduce to reduce the arrays to an integer through the sum of each entry's value.
const categoryValues = _.map(groups, (element) => {
return {
categoryName: ???????,
//*I DONT KNOW WHAT GOES HERE ^,
//I NEED THE NAME OF THE CATEGORY TO BE HERE*
categoryValue: _.reduce(element,(acc, el) => el.value,0),
};
});
Thats because my graph api needs his dataset array to be formed by objects like this one:
{
"categoryName": "cat1", //*THIS IS MISSING*
"categoryValue": 999
}
How can I access the key name of each array? I need to know how the category is named, so that the graph will display its name.
What needs to be written where I put my question marks?
You can get the name of the category from the second parameter of the callback function. This callback function is called by the lodash library and when it calls map function 3 arguments (value, key, collection). map
const categoryValues = _.map(groups, (element, name) => {
return {
categoryName: name, //I DONT KNOW WHAT GOES HERE, I NEED THE NAME OF THE CATEGORY TO BE HERE*
categoryValue: _.reduce(element, (acc, el) => el.value, 0),
};
});
The documentation for map says:
Creates an array of values by running each element in collection thru
iteratee. The iteratee is invoked with three arguments: (value,
index|key, collection).
As you can see, the second parameter passed to the iteratee is the original key in the collection. So, just add another parameter to the iteratee and use that:
const categoryValues = _.map(groups, (element, name) => {
return {
categoryName: name,
categoryValue: _.reduce(element,(acc, el) => el.value,0),
};
});
// this is the simple way.
var arr = {
iamkeysA : [1,2,3],
iamkeysB : [4,5,6]
}
var keys_ = Object.keys(arr); // now you get the list of keys name.
console.log( keys_[0] );
console.log( keys_[1] );

Mapping data from two dictionary and make a resultant one with specific format in javascript

I have a two dictionaries:
featurePermissionMap = {'2':2,'3':1,'4':1} where key is the feature id and it's value represents the permission type.
Like '2':2 means for a feature id 2 we have a permission 2(Read and Write)
and '3':1 means for a feature id 3 we have a permission 1(Read-Only)
Second Dictionary:
feature_with_sub_feature =
[
{ name: 'FeatureA',
subfeatures: [
{ id: 2, name: 'Feature2' },
{ id: 3, name: 'Feature3' },
},
.......
];
I need a resultant dictionary like below:
read_write_access_feature = {
'read':{},
'write':{}
}
I just want to iterate over feature_with_sub_feature and based on subfeature id, I want output like
read_write_access_feature = {
'read':{'FeatureA':['Feature3',....],......},
'write':{'FeatureA':['Feature2',.....],....}
}
I am trying to achieve this using the two forEach. I am new to javascript.
Any optimized way would be much appreciated.
Any help/suggestions would be much appreciated.
Added function getFeatureWithPermission which will return features with permission passed in parameter. Added code explanation in comment.
call getFeatureWithPermission will required permission as below.
let read_write_access_feature = {
'read': getFeatureWithPermission(1),
'write': getFeatureWithPermission(2)
};
Try it below.
let featurePermissionMap = {'2': 2, '3': 1, '4': 1};
// return features with permission passed in parameter.
function getFeatureWithPermission(permission) {
// use reduce to update & return object as requiment
return feature_with_sub_feature.reduce((a, x) => {
// return object with key as x.name
// value as array of names from subfeatures which have respective permission
// first filter subfeatures for respective permission
// then use map to select only name from subfeatures
a[x.name] = x.subfeatures
.filter(y => featurePermissionMap[y.id] === permission)
.map(y => y.name);
return a;
}, {}); // <- pass empty object as input
}
let feature_with_sub_feature = [{
name: 'FeatureA',
subfeatures: [
{ id: 2, name: 'Feature2' },
{ id: 3, name: 'Feature3' },
]
}];
let read_write_access_feature = {
'read': getFeatureWithPermission(1),
'write': getFeatureWithPermission(2)
};
console.log(read_write_access_feature);

Return JSON Object by Value of a Key

I have a huge nested JSON object, and need to find a specific one by a certain value of a certain key.
For example:
[ {
id: 't53',
action: 'Boot',
time: 2019-04-21T17:58:34.579Z
},
{
id: 't54',
action: 'Reset',
time: 2019-04-24T17:57:33.549Z
} ]
So, if need to find the object where action is Boot, and the result must be:
{
id: 't54',
action: 'Boot',
time: 2019-04-24T17:57:33.549Z
}
You can use the Array.find method to get the first item that matches the condition.
const item = objs.find(obj => obj.action === 'Boot');
If you want to find the first element from last, you could create a shallow copy of the array and reverse it.
const item = objs.slice().reverse().find(obj => obj.action === 'Boot');
var data = [{
id: 't53',
action: 'Boot',
time: '2019-04-21T17:58:34.579Z'
},
{
id: 't54',
action: 'Boot',
time: '2019-04-24T17:57:33.549Z'
}];
var result = data.filter(a => a.action === 'Boot');
console.log(result);
You loop over the array and check each item action key is you want or not.

underscore js - finding a nested object

I have an underscore filter which is returning the parent object which contains a child object I am looking for. But I want it to return just the child object. Since it is already doing the work of locating the child object in order to return the parent, I'm wondering how to simplify my code to return just the child. Here's the example:
var filterObj = _.filter(filtersPath, function(obj) {
return _.where(obj.filters, {id: prefilterCat}).length > 0;
});
So here, that nested object inside obj.filters, with the id of prefilterCat, is the object I want returned, not its parent. So currently I would have to do another find inside of filterObject to get what I need. Any ideas?
Underscore's filter method will return the "parent" object but will filter out the ones that don't match the conditional statement. That being the case, if there is only 1 result, then you can just access it similarly to how you would access an array. For instance:
var filterObj = _.filter(filtersPath, function(obj) {
return _.where(obj.filters, {id: prefilterCat}).length > 0;
})[0];
The above example would get the first child that is returned from the filter method.
From your question and code, I'm assuming a data structure like this:
var filtersPath = [
{
filters: [
{id: 0},
{id: 1}
]
},
{
filters: [
{id: 5},
{id: 42}
]
}
];
Now you can get an array of all "parent objects" (which you already have done) that have a filters array containing a object with matching ID:
_.filter(filtersPath, function(obj) {
return _.find(obj.filters, { id: 5 });
});
The advantage of doing it this way is that it will stop searching for a value once it's found one, and not always traverse the entire list.
If you want to actually get an array as result, it's a simple map operation:
_.chain(filtersPath)
.filter(function(obj) {
return _.find(obj.filters, { id: 5 });
})
.map(function(obj) {
return obj.filters;
})
.value();
If you only want to get the first matching object, you don't even need to use a filter or map:
_.find(filtersPath, function(obj) {
return _.find(obj.filters, { id: 5 });
})
.filters;
With lo-dash, this operation will be a little easier:
_.find(filtersPath, { filters: [{ id: 5 }] }).filters

Categories

Resources