I have got array of var players = [] that holds info like userID, userScore etc.. usually I would select specific player by doing something like players[i] where i is a number position in array. But for one bit of my application I do not know this number, but I do know userID And I'm trying to figure out how to update userScore in players array where userID is equal to something, lets say abc_123
for(var i = 0; i < players.length; i++){
if(players[i].userId === 'someId'){
//doSomething(player[i]);
players[i].userScore = 'abc_123';
}
}
You could use the Array.find method:
var players = [ { userId: 123 } ];
var user = players.find(function(item) {
return item.userId === 123;
});
if (user != null) {
// user is the first element in the players array that
// satisfied the desired condition (a.k.a user.userId === 123)
}
Assuming the array items are objects, you can use the filter function:
var player = players.filter(function(p)
{
return p.userID == "something";
}).forEach(function(p) {
p.userScore = "something";
});
You could use the filter function.
var findId = 'jkl';
var theGoose = players.filter(function(user){ return user.userId === findId; }).pop();
var players = [
{
userId: 'abc',
userInfo: 'duck'
},
{
userId: 'def',
userInfo: 'duck'
},
{
userId: 'ghi',
userInfo: 'duck'
},
{
userId: 'jkl',
userInfo: 'goose!'
},
{
userId: 'mno',
userInfo: 'duck'
}];
var findId = 'jkl';
var theGoose = players.filter(function(user){ return user.userId === findId; }).pop();
$('#debug').text( theGoose.userInfo );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="debug"></div>
You might want to use a Dictionary rather than an array. The key can naturally be the player ID. The rest of the information can be put in some object type. Then you can easily access the Dictionary by key.
Try with grep:
var players = [
{score: 10,userId: 1},
{score: 20,userId: 2},
{score: 30,userId: 3}
];
function findByUsrId(id){
return $.grep(players, function(item){
return item.userId == id;
});
};
console.log(findByUsrId(2));
Jsfiddle here: http://jsfiddle.net/pfbwq98k/
Related
I created an empty array in localStorage
localStorage.setItem('items', JSON.stringify([]))
and then fetching that empty array like this :
let fetchedItems = JSON.parse(localStorage.getItem('items'));
After fetching the Array I want to append some objects in the same.
Array of Objects
let objects = [
{
id: '37f60b13-bb3a-4919-beff-239207745343',
body: '1',
},
{
id: '26c5b0fa-b15f-4a50-9a56-5880727a8020',
body: '2',
},
{
id: '37f60b13-bb3a-4919-beff-239207745343',
body: '1',
},
];
The first and last object have same id
Right now what I am doing is, as I don't want to save or append duplicate objects (by id key) in array/localstorage:
function saveItemsInLocalStorage(item) {
let items;
if (localStorage.getItem('items') === null) {
items = [];
} else {
items = JSON.parse(localStorage.getItem('items'));
}
items.push({
id: item.id,
body: item.body,
});
localStorage.setItem('items', JSON.stringify(items));
}
objects.forEach((object) => {
fetchedItems.forEach((fetchedItem) => {
if (fetchedItem.id !== object.id) {
saveItemsInLocalStorage(object)
}
});
});
The above code is not working. I have also tried reduce method.
Note initially array is empty
Let us take an example and try understanding , how you can do it with your code :
let obj = {name:"user",id:1};
let arr = [{name:"user",id:2},{name:"user",id:3}];
let present = false ;
arr.map(val=>{
if(JSON.stringify( {...val})===JSON.stringify({...obj}) )
present = true ;
})
if(present)console.log("The object is present")
else console.log("The object is not present");
I am making a service call where I get back some data. For example:
var response = [
{id: 1, name: 'text1'},
{id: 2, name: 'text2'}
];
This array represents the most possible data I could get back. In other instances I may get back an empty array, an array with only one of those objects(either or of the objects inside the array).
I'd like to somehow loop through my array and check the id of each on=bject to set a flag for the front end to display other data. How do I properly do checks for the id's in the array for the scenarios I mentioned above?
Use Array.some()
var response = [{ id: 1, name: "text1" }, { id: 2, name: "text2" }];
var exists = (id, arr) => arr.some(e => e.id === id);
var id1Exists = exists(1, response);
var id2Exists = exists(2, response);
var id3Exists = exists(3, response);
console.log({ id1Exists, id2Exists, id3Exists });
var response = [
{id: 1, name: 'text1'},
{id: 2, name: 'text2'}
];
let flag
response.length > 0 && response.forEach(el => {
// JUST CHECKING IF ID IS PRESENT AND EQUAL TO 1
// YOU CAN CHANGE ACCORDINGLY
flag = el.id && el.id === 1 ? true : false
})
console.log(flag)
Here I write a function to find a certain object inside your array, I think this must help you:
public function getMyId($myArray, $id)
{
foreach($myArray as $key => $element){
$arrayFromObject = (Array) $element;
foreach($arrayFromObject as $keyObject => $valueObject){
if($valueObject['id'] == $id)
{
return $myArray[$key]->$keyObject;
}
}
}
return null;
}
For each element inside your array I convert object to array to verify if its id is equal to id u're looking for, than I return the array at certain position and certain value, or if you prefer u could just return the $valueObject it will be an array. I hope help u;
I have an array of post that is call test and the next code takes other array and push the post if the name equals something:
var test = [];
docs = [{name: 'mateo',lastName: 'mateo'},
{name: 'Jhon',lastName: 'smith'}}]
docs.forEach(function(item) {
if(item.name === 'mateo'){
test.push(item);
}
});
I want to use different parameters for the name, but I don´t know how, I was trying to use something like this but it did´t work:
var test = [];
docs = [{name: 'mateo', lastName: 'mateo'},
{name: 'Jhon',lastName: 'smith'}}]
const varNames = ['name','lastName'];
docs.forEach(function(item) {
for(i = 0; i < varNames.length; i++){
if(item.[varNames[i]] === 'mateo'){
test.push(item);
console.log(varNames[i]);
}
}
});
That's not how bracket notation work. Change
if(item.["varNames[i]"] === 'mateo') {
To:
if(item[varNames[i]] === 'mateo') {
By the way, you should break the loop once an item is matched:
if(item[varNames[i]] === 'mateo') {
test.push(item);
break;
}
You could also replace that whole for loop with another array function called some, so that your whole code looks like:
docs.forEach(function(item) {
var check = varNames.some(function(varName) {
return item[varName] === 'mateo';
});
if(check) {
test.push(item);
}
})
Which can be shorter if you use an arrow function:
docs.forEach(item => {
if(varNames.some(varName => item[varName] === 'mateo')) {
test.push(item);
}
})
You should really be using filter() for this, everything will be easier:
let docs = [
{name: 'mateo', lastName: 'johnson'},
{name: 'Jhon',lastName: 'smith'},
{name: 'Mark',lastName: 'mateo'}
]
var test = docs.filter(item =>item.name === "mateo")
console.log(test)
Then to check for an array of names you can simple use some() to see if some of the properties match:
let docs = [
{name: 'mateo', lastName: 'johnson'},
{name: 'Jhon',lastName: 'smith'},
{name: 'Mark',lastName: 'mateo'}
]
const varNames = ['name','lastName'];
var test = docs.filter(item => varNames.some(name => item[name] == 'mateo'))
console.log(test)
The trick is to iterate over both varNames and docs. You're familiar with .forEach, so this example uses it, though this may be a better case for .filter.
const test = [];
const varNames = ['name', 'otherName'];
const docs = [
{ name: 'mateo' },
{ name: 'name' },
{ name: 'otherName' }
];
varNames.forEach(varName => {
docs.forEach(doc => {
if (doc.name === varName) test.push(doc);
});
});
console.log(test);
I have been doing some sorting and still dont get it why the result is []. could you guys help me out what im missing?
I have my raw array object:
var data = [
{message:'hello', username:'user1'},
{message:'data', username:'user1'},
{message:'sample', username:'user2'},
{message:'here', username:'user2'},
];
my function is:
var chat = [];
function reorder(obj) {
obj.forEach( function(val, i) {
if(typeof chat[val.username] === 'undefined') {
chat[val.username] = [];
chat[val.username].push(val);
}
else
chat[val.username].push(val);
});
return chat;
}
and on my console:
reorder(data);
I am expecting to have:
var data2 = [
'user1': [{message:'hello', username:'user1'}, {message:'data', username:'user1'} ],
'user2': [{message:'sample', username:'user2'}, {message:'here', username:'user2'} ],
];
You can do this easily with reduce:
var data2 = data.reduce(function(acc, x) {
acc[x.username] = (acc[x.username] || []).concat(x)
return acc
},{})
/*^
{ user1:
[ { message: 'hello', username: 'user1' },
{ message: 'data', username: 'user1' } ],
user2:
[ { message: 'sample', username: 'user2' },
{ message: 'here', username: 'user2' } ] }
*/
The problem is that you made chat an array. When you look at an array in the console, it only displays the numeric indexes, not the named properties; you have to use console.log(chat) to see the named properties.
Since you want this to be an object with named properties, you should declare it as an object, not an array:
var chat = {};
Use Underscore's _.groupBy:
_.groupBy(data, 'username')
I want to implement some sort of hasObject function with underscore.js.
Example:
var Collection = {
this.items: [];
this.hasItem: function(item) {
return _.find(this.items, function(existingItem) { //returns undefined
return item % item.name == existingItem.name;
});
}
};
Collection.items.push({ name: "dev.pus", account: "stackoverflow" });
Collection.items.push({ name: "margarett", account: "facebook" });
Collection.items.push({ name: "george", account: "google" });
Collection.hasItem({ name: "dev.pus", account: "stackoverflow" }); // I know that the name would already be enough...
For some reason underscores find returns undefined...
What am I doing wrong?
It looks like you are reading underscore documentation too literally, where
they have:
var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
However, this doesn't make any sense for your case, you just want to see if the .name property is equal to
some other object's .name, like this:
var Collection = {
items: [],
hasItem: function(item) {
return _.find(this.items, function(existingItem) { //returns undefined
return item.name === existingItem.name;
});
}
};
You need to check both values for the name and the account.
var Collection = {
this.items: [];
this.hasItem: function(target) {
return _.find(this.items, function(item) {
return item.name === target.name && item.acount === target.account;
});
}
};
Have you considered using Backbone.js? It fulfills all your collection management needs and uses underscore's methods too.
// create a collection
var accounts = new Backbone.Collection();
// add models
accounts.add({name: 'dev.pus', account: 'stackoverflow'});
accounts.add({name: 'margarett', account: 'facebook'});
accounts.add({name: 'george', account: 'google'});
// getting an array.
var results = accounts.where({ name: 'dev.pus', account: 'stackoverflow' });