extracting a list of 2 property values - javascript

I have an object array:
user :[
{
name: String,
username: String
}
]
I want to view every change either to name or username.
I found underscore _.pluck only does the trick for one property (_.pluck(user, 'name')
Is there another way to have the list of both values?

With pluck you can only use one property, it simply isn't made to retrieve multiple. The method you would want to use is map, as suggested in this relevant question + answer: How to pluck multiple attributes from a Backbone collection?

Assuming you want the following output [['nameA','usernameA'],['nameB','usernameB'],...]], you could use map in the following manner:
var myResult = users.map(function(user) {
return [user.name, user.username];
});
NOTE: I changed the variable user to users to make more sense with your data.

Related

How to store key value pairs in JavaScript

I'm new to JavaScript and I want a Data Structure for my JavaScript code which stores Student data as key value pairs. The key is the student Registration number and the value is the students name.What I'm thinking is to create a JavaScript object as follows and store data as follows
let Student={
001A:"John",
002A:"Mathew"
};
Is this approach is correct? And if it is correct suppose a way to dynamically add key value pairs to that. Thank you
That would be an object literal. You'd want the key to be a string, but other than that you've basically got it. You can dynamically add properties using bracket syntax. I've attached a small snippet to give you an idea of how it works. :)
let Student={
"001A":"John",
"002A":"Mathew"
};
Student["003A"] = 'Jessica';
Object.entries(Student).forEach(entry => console.log(entry) );
The approach is correct. Given
const students={
'001A': 'John',
'002A': 'Mathew',
};
(Note: It's a good idea to keep your key as a string to prevent collisions with reserved keywords)
To read from the structure you can access the given record via
console.log(students['001A']); // => 'John'
To add new records dynamically, you just add a new property and assign it the desired value:
students['007'] = 'Ben';
which results in
console.log(students);
// =>
{
'001A': 'John',
'002A': 'Mathew',
'007': 'Ben',
};
To delete a given record you can do either
delete students['007'];
or
students['007'] = undefined;
The first option is a little "cleaner" as it completely deletes the given key, along with its assigned data.
Keep in mind that the data will be removed once you reload the page.

How do I see if a character exists within each instance of the array as I type within an array of objects?

I've been struggling with this issue so I thought I'd come here to find the fix. I'm trying to filter my objects that are in an array to only show the ones that have for example "h" in them.
This is how my array of objects is being constructed:
Object.keys(data.jello).forEach(function (id, SomeSearchValue) {
var jello = data.jello[id];
array.push({
id: jello.id,
name: jello.name,
type: 'foo',
});
}
For example, let's say my array consists of this for names.
array[blue, red, green, apple, abigail, alien]
So, I have an array of objects. In a search bar I type "a" and my array results are then all objects that have a letter 'a' in the name. so...
array[abigail, alien]
Then i type a "b" so my search is now "ab" and my array is ...
array[abigail]
So what would my code to implement this using jQuery?
The part I'm stuck on most is the actual searching as the user types without using ajax.
I'm using jQuery. Ive tried things like jQuery.grep(), inArray() but cant seem to search includes. I've also tried array.includes(). Thanks for the help!
Use Array#filter().
jQuery $.grep() is basically the same thing but also works on jQuery objects.
Following assumes you only want to search within name property and will accept the term found in any part of the name rather than just at beginning
const data = [{name:'blue'}, {name:'red'}, {name:'green'}, {name:'apple'}, {name:'abigail'}, {name:'alien'}];
const term ='ab';
const filtered = data.filter(({name}) => name.toLowerCase().includes(term.toLowerCase()))
// or use startsWith() to only match beginning of string
console.log(filtered)

how to access key/value pairs from json() object?

I'm calling an external service and I get the returned domain object like this:
var domainObject = responseObject.json();
This converts the response object into a js object. I can then easily access a property on this object like this
var users = domainObject.Users
Users is a collection of key/value pairs like this:
1: "Bob Smith"
2: "Jane Doe"
3: "Bill Jones"
But CDT shows users as Object type and users[0] returns undefined. So how can I get a handle to the first item in the collection? I'm assuming that some type of type cast is needed but not sure how I should go about doing this
UPDATE
Here is one way I could access the values:
//get first user key
Object.keys(responseObject.json().Users)[0]
//get first user value
Object.values(responseObject.json().Users)[0]
But I need to databind through ng2 so I was hoping for a simpler way like this:
<div>
<div *ngFor="let user of users">
User Name: {{user.value}}
<br>
</div>
</div>
Maybe I should just create a conversion function in my ng2 component which converts the object into what I need before setting the databinding variable?
UPDATED ANSWER
So after scouring through a few docs I found the "newish" Object.entries() javascript function. You can read about it here. Pretty cool.
Anyways, give this a try. I am ashamed to say that I don't have time to test it, but it should get you going in the right direction.
usersArray = []
// Turn Users object into array of [key, value] sub arrays.
userPairs = Object.entries(users);
// Add the users back into an array in the original order.
for (i=0; i < userPairs; i++) {
usersArray.push(_.find(userPairs, function(userPair) { return userPair[0] == i }))
}
ORIGINAL ANSWER
I would use either underscore.js or lodash to do this. Both are super helpful libraries in terms of dealing with data structures and keeping code to a minimum. I would personally use the _.values function in lodash. Read more about it here.. Then you could use users[0] to retrieve the first item.
The only caveat to this is that lodash doesn't guarantee the iteration sequence will be the same as it is when the object is passed in.
users = _.values(users);
console.log(users[0]);
How about this:
let user= this.users.find(() => true)
This should return the "first" one.
If your initial object is just a plain object, how do you know it is sorted. Property members are not sorted, ie: looping order is nor guaranteed. I´d extract the user names into an array and the sort that array by the second word. This should work (as long as surnames are the second word, and only single spaces are used as separators).
var l=[];
for(var x in users) {
push.l(users[x]);
}
var l1=l.sort ( (a,b) => return a.split(" ")[1]<b.split(" ")[1]);

How can I manually access a third-dimension javascript Array

I've been trying to access a third level node in an array using the indexes in it, but I can't access it, I tried a lot of ways that I found here on SO but I don't want to iterate through it, I want to get it manually.
var data = [
{code:1,
label:'John Doe',
tasks:[{
code:1,
label: 'AnyProject',
starts:'2016/1/25',
ends:'2016/2/25'}]
}];
What I want to do (theoretically):
data[0].tasks.code
data[0].tasks[0].code
tasks is an Array so you need to access it like an array.
data[0].tasks[0].code
Inside data array you have tasks and inside task array you have property code.
[] is an array you can use index to look inside.
{} is an object you can access using .

backbone find on collection

I know the method to find a model in a collection from a single attribute,
var musketeers = friends.where({job: "Musketeer"});
but if i want contemporary find by two attribute and return a single result?
My idea is to find once a time the single attributes and after connect the two result:
var name = friends.where({name: "stefano"});
var surname = friends.where({surname: "maglione"});
and after connect the results.
I need because i'm coding a search function to find people based on name and surname.
But there is another problem:if user insert before name and after surname or vice versa?
You could also use the filter method to achieve it
var musketeers = friends.filter(function(friend) {
return friend.get('job') === stefano' && friend.get('surname') === 'maglione';
});
Collection.where in fact accepts multiple attributes:
where collection.where(attributes)
Return an array of all the models in a collection that match the passed attributes.
Useful for simple cases of filter.
You could write your request as
var found = friends.where({
name: "stefano",
surname: "maglione"
});
See http://jsfiddle.net/nikoshr/kuLYE/ for a demo

Categories

Resources