Vue.js Javascript remove from list - javascript

I've got a votes array with users. Now I would like to remove a user
based on his id.
role: 2
active: 2
about: null
id: 3
email: "test#gmail.com.com"
created_at: "2016-11-08 17:14:16"
function: "functie...."
last_name: "Janssen"
mobile: "6"
pivot: Object
updated_at: "2016-11-08 17:30:20"
Method:
option.votes.$remove($root.user.id);
Obviously this is not working. How do I get this to work?

Try this:
newArray = myArray.filter(function( obj ) {
return obj.id !== 'idToDelete';
});
option.votes = newArray

Related

JavaScript (ReactJS) comparing two Objects

I have an object with users:
const data = [
{
name: "John",
lastName: "Doe",
email: "stefa#gmail.com",
password: "123",
following: [{ id: "113"}, { id: "111" } }],
id: "112",
},
{
name: "Jane",
lastName: "Doe",
email: "dusica#gmail.com",
password: "123",
following: [{ id: "112" }],
id: "113",
},
{
name: "Mark",
lastName: "Twain",
email: "marko#gmail.com",
password: "123",
following: [],
id: "111",
},
];
As you can see all users have an array named "following", and that array contains id's of users which the user follows. I want to access that array "following" to find out which users are not followed. Let's say that we want to check the "following" array of the first user John Doe with id="112".
const followers = [];
let suggestions = null;
props.users.forEach((user) => {
if (user.id === '112') {
user.following.forEach((item) => {
followers.push(item);
});
}
});
followers.map((item) => {
suggestions = props.users.map((user) => {
if (user.id !== item.id && user.id !== '112) {
console.log(item.id);
return <div>something</div>;
}
});
});
I tried something like this, but the result is not what i expected to be. As i said, i want to return users that are not followed and render them because i want them to be visible so the user can follow them. I hope that i was understandable enough. Thanks.
It's a negative comparison.
So you want to filter out all users that a user IS following.
You can loop through each user and compare it against the following array. If the following array contains the user then don't show it.
const notFollowing = allUsers.filter(user =>
!currentUser.following.some(({ id }) => id === user.id)
);

Check if the User Id stored in an object in an array is equal to the Id of the Authenticated user

Here's the structure of the array:
post: [
comments: {
userId: 123123123,
name: John doe
}
]
I want to check if the authenticated user's Id (auth.user.id) exists in any of the the comments stored in the Post array. I want to return a boolean as a result.
I have tried using the find() method and the includes() method but haven't had success.
posts.filter(comments => comments.userId === auth.user.id).length !== 0
this expression will evaluate to true if the user id exists in the posts comments , and evaluate to false otherwise
post: [
comments: {
userId: 123123123,
name: John doe
}
]
its not valid.
it should be this
post : [{
comments : {
userId: 123123123,
name: 'John doe'
}
}]
or this
post: [
{
userId: 123123123,
name: John doe
}
]
var post = [{
comments : {
userId: 123123123,
name: 'John doe'
}
}]
console.log(post);
var f = userId => post.some(x => x.comments.userId == userId);
console.log(f(123123123))

In JavaScript, how can I store an array of object value into string variable?

I have this object with the following data that I need to store in a variable:
user: [
{
firstname: 'John',
lastname: 'Doe',
roles: [
{
roleId: 18,
displayText: 'accountant',
description: 'accountant'
}
]
}
]
I am looping through this object as such:
let selectedRole = user.roles.map((role, index) => {
return role.displayText
})
selectedRole returns me the following output: ["accountant"]
For example:
John Doe has only 1 role assigned to him -> account
Sam Williams has 3 roles assigned -> program manager, account, admin
let's say if I click on Sam William's details then I want to see all the roles that I assigned to him in not comma separated but in the following layout:
Role 1: program manager
Role 2: account
Role 3: admin
If you want to get all elements of the array as a delimited string, you can use Array.prototype.join: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
let selectedRoles = user.roles.map((role, index) => {
return role.displayText
});
let rolesString = selectedRoles.join();
If selectedRoles is ['accountant', 'admin'] then the value of rolesString will be accountant, admin. The parameter of join is optional, but its value is the delimiter (comma is default).
EDIT
So if you don't want them as one string, but instead you want to display them individually on the screen. How are you displaying them? Are you using Angular or some other library/framework, or are you using plain JavaScript?
If you're using Angular, for example, you'll use its mechanisms for looping over a collection. So:
<ul *ngFor="let role of selectedRoles; let idx = index">
<li>Role {{idx}}: {{role}}</li>
</ul>
If you don't need an array, but just the string, then don't use .map:
const user = [
{
firstname: 'John',
lastname: 'Doe',
roles: [
{
roleId: 18,
displayText: 'accountant',
description: 'accountant'
}
]
}
];
const selectedRole = user[0].roles[0].displayText;
console.log(selectedRole);
If you want to join all roles into a string, use .join by whatever delimiter you want:
const user = [
{
firstname: 'John',
lastname: 'Doe',
roles: [
{
roleId: 18,
displayText: 'accountant',
description: 'accountant'
},
{
roleId: 20,
displayText: 'somethingElse',
description: 'somethingElse'
}
]
}
];
const selectedRole = user[0].roles.map((r, i) => `Role ${i + 1}: ${r.displayText}`).join('\n');
console.log(selectedRole);

json object from javascript nested array

I'm using a nested array with the following structure:
arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";
now I'm trying to get a nested Json Object from this array
arr{
{
id: example0,
name: name00,
},
{
id: example1,
name: name01,
},
{
id: example2,
name: name02,
}
}
I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.
Thank you!
If you are starting out with an array that looks like this, where each subarray's first element is the id and the second element is the name:
const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]
You first need to map it to an array of Objects.
const arrayOfObjects = array.map((el) => ({
id: el[0],
name: el[1]
}))
Then you can call JSON.stringify(arrayOfObjects) to get the JSON.
You need to make a valid array:
arr = [
{
id: 'example0',
name: 'name00',
},
{
id: 'example1',
name: 'name01',
},
{
id: 'example2',
name: 'name02',
}
];
console.log(JSON.stringify(arr));
Note that I am assigning the array to a variable here. Also, I use [] to create an array where your original code had {}.

check if data is already present in array of objects

I have the following data with me.
var Inputdata = {};
Inputdata.firstName = 'Raul'
Inputdata.lastName = 'Peters'
I want to check if the firstName and lastName (together) is already present in the array of objects. Can someone please let me know how to achieve this.
UserData: [0]
firstName: 'Raul'
lastName: 'Peters'
Id: '4'
[1]
firstName: 'Amil'
lastName: 'Rikia'
Id: '5'
[2]
firstName: 'Riya'
lastName: 'Pillai'
Id: '6'
[3]
firstName: 'Natasha'
lastName: 'Shacke'
Id: '6'
[4]
firstName: 'Eric'
lastName: 'Coles'
Id: '6'
As you can see, Raul Peters is present in the array of objects in one array. I want the output to be true in this case. If Raul and Peters were in different objects, the answer should be false as Raul and Peters are not in the same object. Can anyone please let me know how to achieve this
Just do an Array.some check:
let isPresent = UserData.some(user => user.firstName == 'Raul' && user.lastName == 'Peters')
Use Array.find
arr.find( function(e){
if(e.firstname == 'Raul' && e.lastname == 'Peters')
return e;
});
const inputData = {};
inputData.firstName = 'Raul';
inputData.lastName = 'Peters';
const userData = [
{
firstName: 'Raul',
lastName: 'Peters',
Id: '4'
},
{
firstName: 'Amil',
lastName: 'Rikia',
Id: '5'
},
{
firstName: 'Riya',
lastName: 'Pillai',
Id: '6'
},
{
firstName: 'Natasha',
lastName: 'Shacke',
Id: '6'
},
{
firstName: 'Eric',
lastName: 'Coles',
Id: '6'
}
];
This function receives 2 arguments: the userData array of objects and the inputData object. Then, it uses the Array.prototype.some() method to see if there is at least one entry within the userData array that is an object matching the inputData object.
function alreadyExists(userData, inputData) {
return userData.some(entry => entry['firstName'] === inputData['firstName'] && entry['lastName'] === inputData['lastName']);
};
console.log(alreadyExists(userData, inputData));
If you wanna use underscore or lodash you can use function _.some. Using internal variable you can get needle element.
var needle = false;
var has = _.some(UserData, function(v) {
return (v.firstName===Inputdata.firstName && v.lastName===Inputdata.lastName) ? needle = v : false;
});
console.log(has)
console.log(needle)

Categories

Resources