Removing a keyword from a value inside an object - JS - javascript

I would like to remove the word ".com" from my object. Currently I can convert the object into a string however my filter is not working.
const items = [
{
company: 'datadog.com'
},
{
company: 'google.com'
},
{
company: 'amazon.com'
},
{
company: 'facebook.com'
}
];
var names = items.map(function(item) {
return item['company'];
});
names.toString();
var filter = names.replace(".com", "");
console.log(filter);

Simply use:
let names = items.map(item => item.company.replace(/[.]com$/, ''));
For each company domain name this returns the domain name with any final '.com' sequence removed.

Using the way you are doing it as a base, you can do something like this.
const items = [...youritems];
var names = items.map(function(item) {
return item['company'];
});
stringNames = JSON.stringify(names)
var filter = stringNames.replace(/.com/g, "");
filteredObject = JSON.parse(filter)
console.log(filteredObject)
But I don't think this is the safest way to go about it, or what you really want (it is not an array of objects). I would do something like this, using es6:
const items = [...youritems];
const newObject = items.map((item) => {
const companyNoCom = item["company"].replace(/.com/g, "")
newItem = {...item, company: companyNoCom}
return newItem
})
console.log(newObject)
This is safer to me, it keeps it an array of objects, and it is cleaner. It uses an arrow function and does not modify the underlying objects.

Related

Get a key in a JavaScript object by its value and rename it

I have a list of variables that I will form into an array with keys and values. However, before making them as array I want to check if any of their values matches a
specific string and change their keys names into something else.
Lets say this is the list of variables
customer1 = "Jack", customerDate1 = "08/13/2021", customer2 = "Michael", customerDate2 = "01/01/2021", customer3 = "Luna",customerDate3 = "03/10/2021";
The array before running condition check will be
data = [{key1:"Jack", keyDate1:"08/13/2021",key2:"Michael", keyDate2:"01/01/2021",key3:"Luna", keyDate3:"10" }];
Lets say the condition is:
customerName = "Jack";
I want the cross check customerName variable with the following variables (customer1,customer2,customer3) and if the condition meets any of them, then their keys in the array changes:
for example the condition meets customer1 then both keys of customer1 and customerDate1 changes to something else, to become something like
data = [{conditionMet1:"Jack", conditionDateMet1:"08/13/2021",key2:"Michael", keyDate2:"01/01/2021",key3:"Luna", keyDate3:"10" }];
I am appreciating any help or guidance.
A little bit tricky as alghoritm but it works:
let data = [{key1:"Jhon", keyDate1:"08/13/2021",key2:"Eric", keyDate2:"01/01/2021",key3:"Jack", keyDate3:"10" }];
let i = 1;
let result = [];
let explored = [];
data.forEach(x => {
let resultObj = {};
for (const [key, val] of Object.entries(x)) {
let newKey = key;
let newKeyDate = null;
if (val === "Jack") {
newKey = "conditionMet" + i;
newKeyDate = "conditionDateMet" + i;
}
if (!explored.includes(key)) resultObj[newKey] = val;
if (newKeyDate) {
resultObj[newKeyDate] = x["keyDate" + i];
explored.push("keyDate" + i)
}
if(!key.includes("Date")) i++;
}
result.push(resultObj)
})
console.log(result)
Basically for each element in data I explore all the entries and if I found condition I add conditionMet1 and conditionDateMet1 to object, otherwise what I found on object itself.
Perhaps not very elegant, but for the example given you could do something like this:
if(specialCondition){
data = [{specialKey1:customer1, specialDate1:customerDate1,key2:customer2...];
}else{
data = [{key1:customer1, keyDate1:customerDate1,key2:customer2...];
}
I don't think it is possible to rename a key but you can always create a new key by
object["newKeyName"] = object.previousKey
And optionally you can remove the old key by
delete object.previousKey
That way you will remove the previous key if you don't want it anymore.
Say you have 6 variables.
customer1, customerDate1, customer2, customerDate2, customer3,customerDate3;
You could make an array, by customer
const data = [{
id: customer1,
date: customerDate1
},{
id: customer2,
date: customerDate2
},{
id: customer3,
date: customerDate3
}];
This is now quite useful. Say you want to know which customer meets some condition. (for example id is "Jack"), using Array.find
const jack = data.find(item => item.id === "Jack");
console.log(jack);
Or to find which customers have a date before "now", using Array.filter
const now = Date.now();
const beforeNow = data.filter(item => item.date < now);
console.log(beforeNow);

A lookup function to match the same IDs in two different arrays of objects and inserting key/value pairs into one of the array of objects

I have 2 different arrays with objects. I want to be basically match an ID from both of the array of objects and then basically take the key value pair from the matching object and add it to the other array's object.
For example this is one of the array of objects
const groups = [{id: "1234"}, {id: "4321}]
The second array would look something like this
const childCategories = [{id: "4321", url:"/b/test"}, {id: "2223", url:"/b/test32"}]
So in this case since childCategories.id = "4321" matches with groups.id = "4321" it would add the url: "/b/test" to the matching ID's to the groups object so the result should be
const groups = [{id: "4321", url: "/b/test"}, {id: "1234}]
It should also only add the url key value pair to the groups object as there can be other properties that shouldn't be added to the groups object.
I have tried using .find but i don't think it's supported by IE11.
This is currently what I've currently tried and it's not quite working properly or probably the most efficient.
const getCategoryUrl = (childCategories, groups) => {
groups.map(group => {
const url = childCategories.find(child => child.id === group.id).url;
childCategories.find(child => child.id === group.id) ? {...group, url} : group
})
return groups
}
You could do it like this, without a find:
childCategories.forEach(cc => {
groups.forEach(g =>{
if(cc.id == g.id){
g.url = cc.url;
}
});
This is, I should point out, pretty horribly inefficient, as it iterates through the groups collection completely for every object in childCategories.
With find it would look something like this:
childCategories.forEach(cc => {
let matchGroup = groups.find(g =>{
return g.id == cc.id;
});
if(matchGroup!=null) matchGroup.url = cc.url;
});
Was it able to get it working with this
const getCategory = (childCategories, groups) => {
let matchGroup;
groups.map(group => {
matchGroup = childCategories.filter(child =>
child.id === group.id ? {...group,url: child.url} : group
)
})
return matchGroup
}

Issue in removing object using Lodash _remove

I am having an Object:
ids = [ "-LIof_e0hPtXKtkc4Uh9", "-LIjBcGO7m7VQ-B3pfYt" ]
If I Iterate using .map function of lodash
_.map(ids, (userID, key) => {
console.log('Lopping userId',userID);
})
it gives me value of each id.
Now when I am trying to remove it using _remove it is not working as expected.
_.remove(ids, (value, key, obj) => value == idToBeRemoved);
Still there is no difference in ids Object.
I am really new to angular4 and using lodash for the first time.
I just wanted to remove a value from ids object and get the remaining object.
Print of console.
I am using firebase and trying to delete data after retrieving it from firebase :
deleteTransactWith(transactWithKey,transactWithUser) {
let currentUser = this._authService.getLoggedInUser();
console.log(transactWithUser.groups)
console.log(Object.keys(transactWithUser.groups).length)
console.log('key To remove',transactWithKey)
for (var key in transactWithUser.groups) {
if (transactWithUser.groups.hasOwnProperty(key)) {
let group = this.firebase.object(`/url/${currentUser.$key}/${key}`);
group.snapshotChanges().take(1).subscribe((groupData: any) => {
groupData = groupData.payload.toJSON();
//console.log('not removed',groupData.userIds)
console.log('key',transactWithKey)
_.remove(groupData.userIds, (value) => value == transactWithKey);
//_.pull(groupData.userIds, transactWithKey);
console.log('removed',groupData.userIds)
});
}
}
You want _filter instead
const ids = [ "-LIof_e0hPtXKtkc4Uh9", "-LIjBcGO7m7VQ-B3pfYt" ]
const idToBeRemoved = "-LIof_e0hPtXKtkc4Uh9"
const filteredIds = _.filter(ids, function(id) { return id !== idToBeRemoved})
console.log(filteredIds)
You can simply use lodash _.pull
const _ = require("lodash");
const ids = [ "-LIof_e0hPtXKtkc4Uh9", "-LIjBcGO7m7VQ-B3pfYt" ]
const result = _.pull(ids, "-LIjBcGO7m7VQ-B3pfYt" )
console.log(filteredIds)
First find the index of what you are removed item and next pull out from it by _.pullAt(lodash)
let getIndex= _.findIndex(this.images, function(o) { return o.name == img.name; });
let removedImage = _.pullAt(this.images, getIndex) ;

How to map an Array to an Object in Javascript?

I'm using array.map to iterate through DOM elements in nodejs/cheerio.
There is my code:
const $ = cheerio.load(html);
const lis = $("table[id*='sortable-']").find('tr');
const lisy = lis.map((i, li) => {
var name = $(li).find('td.h-text-left.over-s-only').text();
var cnt = $(li).text();
return {
content: cnt
}
}).get();
And now, I want to return named objects by "name" variable, but for now, .map returning iterated objects:
0: {"cnt": content}, 1: {"cnt": content}
Insted of this, I want to get objects indexed by every "name" like this:
name: {"cnt": content}, name: {"cnt": content}
Is it possible to name returned object like this?
You can achieve your goal by using Array.prototype.reduce
var result = lis.reduce(function(map, li) {
var name = $(li).find('td.h-text-left.over-s-only').text();
var cnt = $(li).text();
map[name] = { content: cnt };
return map;
}, {});

storing key value pairs in an array in javascript

I have 2 arrays namely,
configdata = ["assignee", "shortDesc"];
ticketarray = ["Tom","testDesc"];
I want to store the values as a key value pair in another array, something like this:
ticketData = ["assignee":"Tom","shortDesc":"testDesc"];
Kindly note that the array values are dynamic, so I cannot hardcode them.
Is there a way to do so? I am able to achieve the above said requirement but the length always shows 0. This is the code that I am using:
configdata.Incident_Field.forEach(function (k, i) {
this[k] = ticketarray[i];
}, ticketData);
Other people have explained why your code did not work. I am providing another solution using reduce.
const configdata = ["assignee", "shortDesc"];
const ticketarray = ["Tom", "testDesc"];
let ticketData = configdata.reduce((result, value, index) => {
result[value] = ticketarray[index];
return result;
}, {});
console.log(ticketData);
Output:
{
assignee: "Tom",
shortDesc: "testDesc"
}
The below is not a valid structure in JavaScript:
ticketData = ["assignee":"Tom","shortDesc":"testDesc"];
What you need is a JavaScript object. The best you can do is:
Make sure both the array lengths are same.
Associate the key and value by creating a new object.
Use Object.keys(obj).length to determine the length.
Start with the following code:
configdata = ["assignee", "shortDesc"];
ticketarray = ["Tom", "testDesc"];
if (configdata.length == ticketarray.length) {
var obj = {};
for (var i = 0; i < configdata.length; i++)
obj[configdata[i]] = ticketarray[i];
}
console.log("Final Object");
console.log(obj);
console.log("Object's Length: " + Object.keys(obj).length);
The above will give you an object of what you liked, a single variable with all the values:
{
"assignee": "Tom",
"shortDesc": "testDesc"
}

Categories

Resources