get first 2 charater from an object using JS [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 1 year ago.
i wanted represent first two letters of phone number,i want to get phone numbers first two characters. what i have tried is below Get first two of attribute and find target based on it.
let object = [
"key": {
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
}]
what i have tried is below
object[0].substr(0,2);

let test = {
key: {
"login-attempt": 1,
name: "ADMIN",
phone: "0777123456",
}
};
console.log(test.key.phone.substr(0,2));

You're more likely to have an object like this:
let object = {
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
};
In this case, your code might be:
let prefix = object.phone.substr(0,2);
Or you might have an array of objects:
let object = [
{
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
},
{
login-attempt: 1
name: "CLERK"
phone: "2222222222"
}
];
You can get the 1st two characters of the second element like this:
let prefix = object[1].phone.substr(0,2);
If the element was nested within "key":
let object = {
key: {
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
}
};
let prefix = object.key.phone.substr(0,2);
And so on...

Related

why users and newUser are not equal? [duplicate]

This question already has answers here:
How to compare arrays in JavaScript?
(61 answers)
Closed 12 months ago.
const users = [
{name:'John',age:24},
{name:'Victor',age:28}
];
const newUser = JSON.parse(JSON.stringify(users));
console.log(users);
console.log(newUser);
console.log(typeof(users));
console.log(typeof(newUser));
console.log(users==newUser)
OUTPUT:
[ { name: 'John', age: 24 }, { name: 'Victor', age: 28 } ]
[ { name: 'John', age: 24 }, { name: 'Victor', age: 28 } ]
object
object
false
object users and newUser have exactly same items and values.
They why users==newUser is false?
In Javascript the equals operator compares object instances, not values. They are 2 different instances, so not equal.
One way to compare the values is to use a deep equals library. Another way is to compare the JSON.stringify value.
JSON.stringify(users) === JSON.stringify(newUser) // true
A caveat of the stringify approach is that undefined values are stripped.

I have array with objects, I need to fetch all the objects that matches the value of userId starts with 'US' [duplicate]

This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed last year.
Below is the array with objects:
myArray:[
{"name":"Ram", "email":"ram#gmail.com", "userId":"HB000006"},
{"name":"Shyam", "email":"shyam23#gmail.com", "userId":"US000026"},
{"name":"John", "email":"john#gmail.com", "userId":"HB000011"},
{"name":"Bob", "email":"bob32#gmail.com", "userId":"US000106"}
]}
I tried this but I am not getting output:
item= myArray.filter(element => element.includes("US"));
I am new to Angular.
let filteredArray = myArray.filter(function (item){
return item.userId.substring(0,2).includes('US')
})
Console.log(filteredArray)
//Output
[ { name: 'Shyam', email: 'shyam23#gmail.com', userId: 'US000026' },
{ name: 'Bob', email: 'bob32#gmail.com', userId: 'US000106' } ]
As noted by #halfer - You need to filter on the property that you are interested in - in this case - 'userId' - you can do this by simply adding the property into the code you already had tried and it will log out the specified items - or alternatively - you can make a utility function that takes the array, property and target string as arguments and this will allo2w you to search / filter other arrays and by any property and target string .
These two options are shown below and both log out the same results.
const myArray = [
{"name":"Ram", "email":"ram#gmail.com", "userId":"HB000006"},
{"name":"Shyam", "email":"shyam23#gmail.com", "userId":"US000026"},
{"name":"John", "email":"john#gmail.com", "userId":"HB000011"},
{"name":"Bob", "email":"bob32#gmail.com", "userId":"US000106"}
]
// option 1 - direct filtering
const matchingItems = myArray.filter(element => element.userId.includes("US"));
console.log(matchingItems);
// gives - [ { name: 'Shyam', email: 'shyam23#gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32#gmail.com', userId: 'US000106' } ]
//option 2 - create a function that takes arguments and returns the matches
const matches = (arr, prop, str) => {
return arr.filter(element => element[prop].includes(str));
}
console.log(matches(myArray, 'userId', 'US'));
// gives - [ { name: 'Shyam', email: 'shyam23#gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32#gmail.com', userId: 'US000106' } ]

Javascript return true if a value exists in a nested array [duplicate]

This question already has answers here:
Check if a value exists in an Array object in JavaScript or Angular
(4 answers)
Closed 3 years ago.
I want to return true if a nested array contains a particular value
In this example I'm trying to see if the users array has the current users id but I get the object instead of true
var currentUserId ="MBsCLlPbilRr26Jpz5oxhMULRvC2"
var users = [
{
id: "MBsCLlPbilRr26Jpz5oxhMULRvC2",
name: "Dennis",
url: undefined,
},
{
id: "CLlPbhMULRvC2jnjnDe",
name: "Dennis",
url: undefined,
},
]
console.log(users.find(user=>user.id === currentUserId))
The problem is you are using .find() instead of .some(). Try the following:
var currentUserId ="MBsCLlPbilRr26Jpz5oxhMULRvC2"
var users = [
{
id: "MBsCLlPbilRr26Jpz5oxhMULRvC2",
name: "Dennis",
url: undefined,
},
{
id: "CLlPbhMULRvC2jnjnDe",
name: "Dennis",
url: undefined,
},
]
console.log(users.some(user=>user.id === currentUserId))
The difference is in the output. .find() will return the value, .some() will return a boolean.

Find top level key in multidimensional object by value of second level key in javascript [duplicate]

This question already has answers here:
Find by key deep in a nested array
(21 answers)
Closed 5 years ago.
I have and multidimensional object that looks like this:
obj = {
'someString': {
name: 'John',
page: 'some url',
number: 4
},
'someString2': {
name: 'Bill',
page: 'some url',
number: 7
}
}
How do I find the first level key (in this case "someString2") where "number" is equal to 7?
The number is always unique and is the only thing I know beforehand.
Here you go. Using Array.find function to look for the appropriate key.
const numberToLookFor = 7;
const data = {
someString: {
name: 'John',
page: 'some url',
number: 4,
},
someString2: {
name: 'Bill',
page: 'some url',
number: 7,
},
};
const myKey = Object.keys(data).find(x => data[x].number === numberToLookFor);
console.log(myKey);

javascript Collection of an object accessible by key [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How can I make this happen in javascript??
People[key1][0].FirstName = "First1-k1";
People[key1][0].LastName = "Last1-k1";
People[key1][1].FirstName = "First2-k1";
People[key1][1].LastName = "Last2-k1";
People[key2][0].FirstName = "First1-k2";
People[key2][0].LastName = "Last1-k2";
People[key2][1].FirstName = "First2-k2";
People[key2][1].LastName = "Last2-k2";
Or maybe:
People[key2].Index[1].LastName = "Last2-k2";
Other clarification:
SomeObject["somekey"][0].FirstName = "whatever";
SomeObject["somekey"][1].FirstName = "whatever";
SomeObject["someotherkey"][0].FirstName = "whatever";
SomeObject["someotherkey"][1].FirstName = "whatever";
Thanks
When using properties and indexes together, you are talking about Objects (which have properties) and Arrays (which have indexes).
Your initial syntax of: People[key1], implies that People is either an array where key1 is a variable holding a non-negative number or People is an Object where key1 is a string the will serve as the name of a property of the object.
So, you could have:
var People = ["John","Paul","Ringo","George"];
var key1 = 3; // Arrays use non-negative numbers as indexes
console.log(People[key1]); // "George"
Or, you could have:
var People = {
first:"John",
last: "Lennon"
}
var key1 = "first"; // Objects use strings as property names
console.log(People[key1]); // "John"
Now, if we continue your code: People[key1][0], you indicate that key1 should be indexed with a number, so that means that People[key1] should return an Array. This would mean that People could be an array containing arrays or an Object with arrays as properties:
Array with nested arrays:
var People = [
["John","Paul","Ringo","George"],
["Moe","Larry","Curly","Shemp"]
];
var key1 = 1;
console.log(People[key1][0]); // "Moe"
Object with arrays as property values:
var People = {
Beatles: ["John","Paul","Ringo","George"],
ThreeStooges: ["Moe","Larry","Curly","Shemp"]
};
var key1 = "Beatles";
console.log(People[key1][0]); // "John"
Finally, when we add your last pieces of syntax: People[key1][0].FirstName, we can see that People[key1][0] must be returning an Object because you are providing a property name to access, so the final structure could still use Array or Objects, but could look like these:
Array with nested arrays that hold objects that have properties:
var People = [
[
{ firstName: "John" },
{ firstName: "Paul"} ,
{ firstName: "Ringo"} ,
{ firstName: "George"}
],
[
{ firstName:"Moe", lastName: "Stooge" },
{ firstName: "Larry", lastName: "Stooge" },
{ firstName: "Curly", lastName: "Stooge" },
{ firstName:"Shemp", lastName: "Stooge" }
]
];
var key1 = 1;
console.log(People[key1][0].firstName); // "Moe"
People[key1][0].firstName = "First-K2";
console.log(People[key1][0].firstName); // "First-K2"
Object with arrays as property values that store objects which have properties:
var People = {
Beatles: [
{ firstName: "John" },
{ firstName: "Paul"} ,
{ firstName: "Ringo"} ,
{ firstName: "George"}
],
ThreeStooges: [
{ firstName:"Moe", lastName: "Stooge" },
{ firstName: "Larry", lastName: "Stooge" },
{ firstName: "Curly", lastName: "Stooge" },
{ firstName:"Shemp", lastName: "Stooge" }
]
};
var key1 = "Beatles";
console.log(People[key1][0].firstName); // "John"
People[key1][0].firstName = "First-K2";
console.log(People[key1][0].firstName); // "First-K2"
Now, while your syntax could mean two different structures that both could work, you really need to spend some time and think about this from the inside out. You appear to have objects with a firstName property as the deepest construct in your structure, but working outward from there, you seem to just be adding layers without any particular reason. Should the objects with firstName properties be enumerable? If so, it makes sense to have them in an array. But, why package them up any further? You need to decide.

Categories