How do we remove particular object from js Map object? - javascript

I have some objects inside js Map object. How do we remove object with particular key and value?
let newMap = new Map()
newMap.set('1', {ep: '1', name: 'First test'})
newMap.set('2', {ep: '2', name: 'Second test'})
So, the above example holds two object inside newMap. How can I remove object with ep value '1', so that the newMap hash returns only one object i.e. {ep: '2', name: 'Second test'}.

You've stored it under the key '1'. So you call delete with that key:
newMap.delete('1');
If you don't know the key you've stored it under, a Map probably isn't the structure you wanted, but you can find it by looping through entries, which returns an array whose entries are arraysin [key, value] format:
for (const entry of newMap.entries()) { // for-of is ES2015+
if (entry[1].ep === '1') {
newMap.delete(entry[0]);
break;
}
}
...or with ES5:
newMap.entries().some(function(entry) {
if (entry[1].ep === '1') {
newMap.delete(entry[0]);
return true;
}
});

You'll have to iterate over the entries and find the object you want to remove, then delete the appropriate key:
let newMap = new Map();
newMap.set('1', {ep: '1', name: 'First test'});
newMap.set('2', {ep: '2', name: 'Second test'});
const entryToRemove = [...newMap.entries()].find(([, { ep }]) => ep === '1');
newMap.delete(entryToRemove[0]);
console.log(newMap); // look in browser console, not snippet console
(Of course, if you can count on the map's key being the same as the ep, just do newMap.delete(epToDelete))

Your map looks like this:
Map { '1' => { ep: '1', name: 'First test' }, '2' => { ep: '2',
name: 'Second test' } }
To remove ep:'1' and have onlye ep:'2' you can try this:
newMap.delete('1');

Related

return a value of array that have special name

Im new in react js and I get a problem with my array... I want to return a value of my array that have contain name and adress .and all value are string thi is my data that I need
name :123,
adress:12569
const array = [
0: [ 'name','123' ],
1: [ 'adress','12569'],
2: ['family','4'],
];
You can run loop on the array and assign key-value for each of the array items.
const array = [
['name', '123'],
['adress', '12569'],
['family', '4'],
];
const res = {};
array.forEach((item) => {
res[item[0]] = item[1];
})
console.log(res);
In this case, you should use an Object.
const foo = {
name: '123',
adress: 'bar',
family: '4',
}
So, to access the propertys:
console.log(foo.name); // 123
console.log(foo.adress); // bar
console.log(foo.family); // 4
But if you are getting this information as an array, you can always transform it into an object.
It would make more sense for that data to be combined into a single object rather than a series of nested arrays, and then use find to locate the object that matches the query.
const data = [
{ name: 'Bob', address: '999 Letsbe Avenue', family: 4 },
{ name: 'Sally', address: '8 Treehouse Lane', family: 0 },
{ name: 'Joan', address: '85 Long Terrace', family: 6 }
];
// Accepts the data array, and a query object
function findFamily(data, query) {
// Iterate through the data array to `find`
return data.find(obj => {
// Split the query into key/value pairs
const queryEntries = Object.entries(query);
// And return only those objects where the
// object key/value matches the query key/value
return queryEntries.every(([ key, value ]) => {
return obj[key] === value;
});
// And if there are no matches return 'No match'
}) || 'No match';
}
console.log(findFamily(data, {
name: 'Bob',
address: '999 Letsbe Avenue',
family: 0
}));
console.log(findFamily(data, {
address: '999 Letsbe Avenue',
family: 4
}));
console.log(findFamily(data, {
name: 'Sally'
}));
Additional documentation
every
Destructuring assignment
Object.entries

How to retrieve certain properties of an array of objects and put it into a new array of objects? [duplicate]

This question already has answers here:
Filter array of objects based on another array in javascript
(10 answers)
Closed 2 years ago.
i have an array of objects like below,
data: [
{
name: 'name1',
id: '1',
description: 'name 1 description',
},
{
name: 'name2',
id: '2',
description: 'name 2 description',
},
{
name: 'name3',
id: '3',
description: 'name 3 description',
},
]
i have an array consisting of ids like so
const id_list = ['1','2'];
Now i want to retrieve the id and name from data array object whose id matches with id_list
so the expected output is
const new = [
{
id: '1',
name: 'name1',
},
{
id: '2',
name: 'name2',
}
]
i am new to using react, javascript or typescript. could someone help me solve this. thanks.
what i have tried?
i know that to filter the value based on one value
so if i have to filter based on one id say '1'
i can do
const new = data.filter((item) => id === item.id);
but in my case i want to filter all items which match the id_list array and should retrieve only matching object name and id and put it to a array.
You can use the map function with a find method to map every id of id_list to the corresponding object in data
const result = id_list.map((id) => data.find((d) => d.id === id));
After that you have all objects that were found by ids in result. You can either only use the props you want or map again and get only the required properties.
const final = result.map(({ id, name })=> ({ id, name }))

How to search within the nested array of objects in javascript?

i want to search a for a string say for example "hello" within 'name' in array of objects. The data structure is like the one below,
[{name:'hello', value: 'value', children: [{ name:'world', value: 'something'}]},
{name:'somename', value: 'value2', children: [{name: 'hello', value: 'value3', children: [{name: 'anothername', value: 'value4'}]},
{name: 'new', value: 'value5'}];
So from the above mentioned data structure, if the search query is say 'hello' i want to check through 'name' field of each object. also check within children 'name' field of each object. Some object may or may not have children and nested children too. I want to retreive the objects that have matched the search query.
For example if my search query is 'hello' then the expected output is as below,
[{name:'hello', value: 'value', children: [{ name:'world', value: 'something'}]},
{name:'somename', value: 'value2', children: [{name: 'hello', value: 'value3', children: [{name: 'anothername', value: 'value4'}]},
i have tried using the below search method but that doesnot search within children and nested children.
search = (query, listitems => {
if (!query) {
return listitems;
}
query = query.toLowerCase();
const results = [];
let counter;
let childcounter;
listitem.forEach((listitem) => {
counter = 0;
childcounter = 0;
if (listitem['name'].toLowerCase().indexOf(query) > -1)
{
counter++;
if (listitem.children)
{
listitem.children.forEach ((child) => {
if (child['name'].toLowerCase().indexOf(query) > -1)
childcounter++;
});
}
listitem.counter = counter;
listitem.childcounter = childcounter;
results.push(listitem);
}
return result
});
How can i do it. could someone help me with it. Thanks.

json object from javascript nested array

I'm using a nested array with the following structure:
arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";
now I'm trying to get a nested Json Object from this array
arr{
{
id: example0,
name: name00,
},
{
id: example1,
name: name01,
},
{
id: example2,
name: name02,
}
}
I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.
Thank you!
If you are starting out with an array that looks like this, where each subarray's first element is the id and the second element is the name:
const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]
You first need to map it to an array of Objects.
const arrayOfObjects = array.map((el) => ({
id: el[0],
name: el[1]
}))
Then you can call JSON.stringify(arrayOfObjects) to get the JSON.
You need to make a valid array:
arr = [
{
id: 'example0',
name: 'name00',
},
{
id: 'example1',
name: 'name01',
},
{
id: 'example2',
name: 'name02',
}
];
console.log(JSON.stringify(arr));
Note that I am assigning the array to a variable here. Also, I use [] to create an array where your original code had {}.

Deep reduce (pluck maybe?) of array of objects

I have lodash to use for this (or underscore). I am trying to take an array of objects and turn them into a boiled down array of objects. Let me show you.
$scope.myObject = [{
name: 'Name1',
subs: [
{
name: 'Sub 1',
subs: [
{
name: 'Sub 1-1',
apps: [
{
name: 'App 1'
}
]
}
],
apps: [
{
name: 'App'
}
]
}
That's the original objects (one node of it at least). And My desired effect is to boil it down to an array of objects that are just the 'apps'. As you see here the apps can fall on any level - so it needs to be some kind of a deep search/reduce. These objects can potentially go 10 levels deep and have an app array on any level. So I'm trying to boil it down to a flat array of just apps, so for example this object would turn into:
[{'name' : 'App 1'},{'name' : 'App'}];
I'm still pretty new to this kind of object manipulation so I could use some guidance. Thanks!
function pluckRecursive(input, prop, collect) {
collect = collect || [];
if (_.isArray(input)) {
_.forEach(input, function (value, key) {
pluckRecursive(value, prop, collect);
})
} else if (_.isObject(input)) {
_.forEach(input, function (value, key) {
if (key === prop) {
collect.push(value);
} else {
pluckRecursive(value, prop, collect);
}
})
}
return collect;
};
when used like
pluckRecursive($scope.myObject, 'apps')
returns:
[[{"name":"App 1"}], [{"name":"App"}]]
Use _.flatten() on that to get rid of the nested arrays.
You may use deep-reduce like this:
const deepReduce = require('deep-reduce')
let apps = deepReduce($scope.myObject, (arr, value, path) => {
if (path.match(/subs\.\d+\.apps\.\d+$/) {
arr.push(value)
}
return arr
}, [], 'subs')
Explanation of the code:
(arr, value, path) => ... is the reducer function. It should always return the accumulated value, here the array of apps. The accumulated value is passed to the reducer as the first argument.
value, is any value in your object tree. It may be the subs array, objects inside the subs array, or leaf values like subs.0.name.
path is where the current value passed is found. For example subs.0.subs.0.apps. Keys of arrays are digits, here 0.
subs\.\d+\.apps\.\d+$ matches any path that ends in subs.digit.apps.digit. I've omitted ^ from the start, since some apps are nested in subs subs. You may try out the regexp here: https://regex101.com/r/n1RfVv/1
[] is the initial value of arr.
'subs' tell deepReduce to start at that path, meaning that name or any other property in the root object will not be traversed.
Speed
Depending on the size of your objects, this might be slow, as deep-reduce traverses the whole object tree. If possible, define the starting path to limit traversal, like 'subs' is given in example above.
If your data source is not changing much, you might want to scrape the data source, clean it up, and provide your own api.
Inner workings
If you are interested in how deep-reduce works, you can read the code here: https://github.com/arve0/deep-reduce/blob/master/index.ts
Here are two solution using object-scan. The first one searches for apps anywhere, the second one only in nested subs.
// const objectScan = require('object-scan');
const myObject = [{ name: 'Name1', subs: [{ name: 'Sub 1', subs: [{ name: 'Sub 1-1', apps: [{ name: 'App 1' }] }], apps: [{ name: 'App' }] }] }];
console.log(objectScan(['**.apps[*]'], { rtn: 'value' })(myObject));
// => [ { name: 'App' }, { name: 'App 1' } ]
console.log(objectScan(['**(^subs$).apps'], { rtn: 'value', useArraySelector: false })(myObject));
// => [ { name: 'App' }, { name: 'App 1' } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
You can do this natively using _.get
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
_.get(object, ['a', '0', 'b', 'c']);
// => 3
_.get(object, 'a.b.c', 'default');
// => 'default'

Categories

Resources