JavaScript remove string from a value within an object - javascript

I have an object:
let Data = {name: 'Flomo', age: 25, address: 'Sinkor', id: 'NMF25'}
I want to console log the entire object but the id value should only contain the last three characters.
Like this:
{name: 'Flomo', age: 25, address: 'Sinkor', id: 'F25'}
I'm doing this:
console.log(Data.replace(/NM/g, ''))
But I got:
TypeError: Data.replace is not a function
Is there an easy way to achieve this?

replace is a method that operates on String, and doesn't change the string in-place.
If you're not worried about changing the original data, you can do this:
let Data = {name: 'Flomo', age: 25, address: 'Sinkor', id: 'NMF25'}
Data.id = Data.id.replace('NM', '')
console.log(Data);
Alternatively, if you're not sure what the first characters of the id will be (or how many there could be), you could do this:
let Data = {name: 'Flomo', age: 25, address: 'Sinkor', id: 'NMF25'}
Data.id = Data.id.substring(Data.id.length-3)
console.log(Data);
If you need to keep the original data intact, you can copy the object, however this can be complicated depending on the data that might be in the object: How do I correctly clone a JavaScript object?

The replace function works on a String. Youre calling that function on an Object.
You probably intended to call replace on the value of the property id. The terms I just used should help you mentally step thru problems like this in the future!
If you look at MDN's documentation for JavaScript, you'll see which functions you can call on which Types and other objects.

Related

Remove key value pair from an object in javascript using underscoreJs

I have an array
var data = {email: 'email#gmail.com', phone: '3434344332', firstName: 'john', lastName: 'Doe'};
How do i remove one or more elements from the array?
I Tried _.without( data, data.email ) , this removes the email field but also changes the Object to array without keys.
result ["3434344332", "john", "Doe"]
What I want to achieve {phone: '3434344332', firstName: 'john', lastName: 'Doe'}
without only works with arrays. If you pass an object, it'll get turned into an array in a similar manner to Object.values. You should be using omit instead:
_.omit(data, "email")
reference
Probably you can just use the vanilla JS
delete data.email
However, this solution modifies the original object (does not make a copy of object with an excluded field).

How to retain the duplicate values during the JSON stringify operation

I am obtaining the response from the server in JSON format. This JSON may constitute objects with duplicate Keys. When I was displaying the result the duplicate key values were getting committed. After debugging I found out that this is happening because of the JSON.stringify method that I am performing to format the code before providing to the front-end.
As of now when I perform the JSON.stringify then it removes the duplicate entries and provides only the last value for the duplicate keys however I would like to retain everything.
var obj = {name: "John", age: 30, name: "New York"};
var result = JSON.stringify(obj).replace(/\_/g, '');
console.log(result);
//{"name":"New York","age":30}
As we can see the first name has been committed. How to modify the code so we can retain all values of the duplicated key?
Please Note:
As of now, I have provided the sample code that has the duplicate key name. However, when I am getting the response from the server I am unaware of what key might be duplicated so I am looking for a general solution that can work for everything rather than hard-coded logic that works only for name.
Any suggestions or workarounds would be really appreciated.
Json objects don't allow duplicated keys.
If you execute just:
var obj = {name: "John", age: 30, name: "New York"};
console.log(obj)
You will see that you have already lost the first "name" value.
The only work around that I can think of, is to never transfor the received JSON String to an Object.
Or you can manually write a logic to split this json string by commas, and transform it into a JSON object according to you need, but without duplicated keys, for example:
{name: ["John", "New York"], age: 30};

Javascript/node.js retrieving value from dictionary key which is in a 2d array

I've never asked a question on here but here goes.
Lets say I have an array (named whatever) that looks like this when displayed:
[[{name: "Joe", price: 42}],[{name: "Smith", price: 34}],[{name: "Jerry", price: 67}]]
And I want to do something like whatever[1].price (this fails in my program) I want to be able to take one of the arrays in whatever and retrieve it like whatever[1].price. Any way to do this similar to an ArrayName[index].key ?
first, your JSON is not correct, see the updated one;
since inner element of array is an array with single item so you can access it with 0 index.
var test = [[{name: "Joe", price: 42}],[{name: "Smith", price: 34}],[{name: "Jerry", price: 67}]];
test.forEach(item=> {
console.log(item[0]['price'])
});
Why does an Array of Objects be stored in an another array? Just remove the extra array initialization if you just want to achieve this
And I want to do something like whatever[1].price
Change the data like this:
[{name: "Joe", price: 42}],[{name: "Smith", price: 34}],[{name: "Jerry", price: 67}]
If you can't change the data, then A.T.'s solution will suffice
Well, based on your response ( which have an unnecessary array which contain an array of objects ) you can access to your data like
whatever[0][0].price
The better way is to change your response in backend to get an array of objects then you can access it like normal
whatever[0].price

Understanding for in loop (javascript)

Im kinda new to JS and I'm trying to understand how for/in loop really works, here's some sample code:
phoneBook = {};
phoneBook.bill = { name : "bill", lastName "hayder" };
phoneBook.steve = { name : "steve", lastName "garcia" };
for ( obj in phoneBook )
{
console.log(obj);
};
When I run this code I get bill and steve as an output, my question is if that's what the iterator holds why I am allowed to do phoneBook[obj] and work with that?? If I type manually phoneBook[bill] I get an error, I can only phoneBook.bill or phoneBook["bill"].
Thanks for helping.
When you write phonebook[something] it means that something should be an expression that returns a string, and it should find the property whose name is that string.
In the case of phonebook[obj], the value of the variable obj will be the string "bill" or "steve", and it will then look up the corresponding property.
If you write phonebook[bill], it tries to use bill as a variable name, and expects it to contain a string that names a property. But there is no variable named bill, so this gets an error.
Javascript objects are simply key-value pairs.
phoneBook = {};
phoneBook.bill = { name : "bill", lastName: "hayder" };
phoneBook.steve = { name : "steve", lastName: "garcia" };
In this example, the phoneBook object has two key-value properties, bill and steve. But the properties themselves are objects, each containing the properties name and lastName.
Key-value pairs can be accessed via two ways: the object way and the dictionary way. Object way means accessing via phoneBook.bill, and dictionary way means accessing via phoneBook['bill']. Notice that using a dictionary way means simply passing the property name to the object.
Now, phoneBook[bill] is invalid because JS thinks that bill is a variable, and tries to find this. That's why you should use phoneBook['bill'] or phoneBook["bill"]. You can use this dictionary form, but I suggest you use the phoneBook.bill method.
I hope I answered your question. :)
some syntax errors fixed
phoneBook = {};
phoneBook.bill = { name: "bill", lastName: "hayder" };
phoneBook.steve = { name: "steve", lastName: "garcia" };
for (obj in phoneBook)
{
console.log(obj);
};
Javascript basics
phoneBook has a property bill
In javascript this property bill can be referenced using
phoneBook.bill
phoneBook['bill']
when you reference phoneBook[bill] you will recieve an error because javascript is looking for a variable that contains the string bill
what you can do is try it this way
var bill = 'bill';
phoneBook[bill]

req.user is a list, I have to do req.user[0].prop to get data. Why is this happening?

Before I was able to do req.user.property to get data, but all of a sudden that failed and I have to do req.user[0].property to get data.
Essentially req.user is a list. It looks like this...
user:
[ { _id: '934715373258035',
active: true,
date: 'July 1st 2015, 1:44:49 am',
email: 'username#emailprovider.com',
genre: '53d8fcd1ea70ad64d6655fa8',
location: '53d8ff38ea70ad64d6655fbb',
name: 'First Last',
pass: 'QAt9tSGDpft7iSxwoa5gsTO63ONXshREQmkE8F6MKqRA6IIn2Eo49Z5vZFqKushX' } ],
Why is this and what is causing it? Is this normal? It didn't seem to be in my research.
As I can see, currently you have array of entities (users), so that's why you can't access your properties just be req.user.propertie.
In order to access some prop. of array, you need to select specific item for this array and then access needed property.
Possible the issue is related to the fact that previously you were receiving jason object and now it's array of json objects.
Example
Array: var objects = [obj1][obj2][obj3];
To select specific item you need to access it by index: objects[0] //obj1
And then you can access properties of 'obj1': objects[0].someProp
It sounds like req.user.property has changed from an object literal to an array. In an object literal, you'd be able to access the property by name.
var objectLiteral = {name: 'foo'};
objectLiteral.name === 'foo' // true
In an array, you have to access the members by index.
var arrayOfObjectLiterals = [{name: 'foo'}, {name: 'bar'}]
arrayOfObjectLiterals[0].name === 'foo' // true
In order to force req.user to be an object (instead of an object within a list) I changed my passport.deserializeUser function to run the command db.users.findOne() instead of db.users.find().
This returns only the first result and allows req.user to be equal to an object instead of a list that contained the object.
Still not sure what originally caused it to turn in to a list since it should still only return one result...

Categories

Resources