remove undefined value from object - javascript

I facing an issue in javascript, i want to remove undefined value from object
Expected Output
Without undefined value ni array.
var result = [
undefined,
undefined,
{
group: '1042000018356',
email: 'xyz#desk.com'
},
{
group: '1042000098595',
email: 'abc#desk.com'
}
]
// This my logic:
result = result.map(function(index){
for (var key in array) { // Looping
if( index == key ){
var group = array[key]; // Group id
var email = key; // Email
return {group , email};
}
}
});
console.log("result", result);
How can i remove undefined value from Object
can anyone help me please?

You can just do a filter and pass on a boolean constructor which will ensure you remove all the null and undefined values from the result array
var result = [
undefined,
undefined,
{
group: '1042000018356',
email: 'xyz#desk.com'
},
{
group: '1042000098595',
email: 'abc#desk.com'
}
]
result = result.filter(Boolean);
console.log(result);

Another way to do it with simple filter() to remove undefined, here the filter internally turns the return value of the callback to Boolean which is similar to Boolean constructor i.e filter(Boolean)
result = [
undefined,
undefined,
{
group: '1042000018356',
email: 'xyz#desk.com'
},
{
group: '1042000098595',
email: 'abc#desk.com'
}
]
result = result.filter(el=>el)
console.log(result);

Try this example :
var newarray = [
undefined,
undefined,
{
group: '1042000018356',
email: 'xyz#desk.com'
},
{
group: '1042000098595',
email: 'abc#desk.com'
}
];
var R = [];
newarray.map(function(item, index , myarray){
// console.log("item -> ", item);
if( typeof item === 'undefined') {
// console.log("undefined detected!");
} else {
R.push(item);
}
});
console.log("result -> ", R);

Related

Is there a way to check for falsy values from an array?

I want to check a bunch of variables for falsy values.
Instead of writing a very long if statement, e.g.:
if (!userData.email || !userData.lastName || ! userData.firstName etc...
I wanted to put these values in an array and simply check the array, e.g.:
var detailsConditionsArr = [
userData.firstName,
userData.lastName,
userData.email,
userData.phone,
userData.address,
userData.mailAddress,
]
if (detailsConditionsArr.indexOf(false) === 1) {
console.log("Found a falsy");
}
But the above doesn't work (if statement never fires).
The values could be false, null or ''.
Is there a way to check these from the array?
Ideal use case for Array#some
Check for falsy value in the iteration, if the test succeeds, true will be returned.
var A = ["Name", ""];
var B = ["Name", "30"];
var C = ["Name", "30", null];
if (A.some(el => !el)) {
console.log("Found a falsy in A");
}
if (B.some(el => !el)) {
console.log("Found a falsy in B");
}
if (C.some(el => !el)) {
console.log("Found a falsy in C");
}
You can use the key names you want to check as an array, then do the check like this:
const userData = { email: '', lastName: '', firstName: '' };
const hasFalsy = ['email', 'lastName', 'firstName'].some(k => !Boolean(userData[k]));
if (hasFalsy) {
console.log('found a falsy');
}
You can use reduce to return a single value from the array like so:
var detailsConditionsArr = [
userData.firstName,
userData.lastName,
userData.email,
userData.phone,
userData.address,
userData.mailAddress,
]
if (detailsConditionsArr.reduce((carry, el)=> el ? carry : true, false)) {
console.log("Found a falsy");
}
You can loop the list of properties and then check if any is falsy :
const userData = {
firstName : 'John',
lastName : 'Doe',
email : null,
phone : 42,
address : 'Hello',
mailAddress : 'world'
};
function HasObjectAnyFalsyValues(obj)
{
for (let prop in obj)
{
if (Object.prototype.hasOwnProperty.call(obj, prop)
&& !obj[prop]) { // <-- check for falsy
return true;
}
}
return false;
}
console.log('The object has ' + (!HasObjectAnyFalsyValues(userData) ? 'no ' : '') + 'falsy values');
This will check all properties. If you want to list specific properties instead, use one of the other answers posted
You can use some method.
var detailsConditionsArr = [
"test",
12,
false,
"s",
"sd",
"test",
]
if (detailsConditionsArr.some(x => !x)) {
console.log("Found a falsy");
}
// or
//if (detailsConditionsArr.some(x => !Boolean(x))) {
// console.log("Found a falsy");
//}
Using some is a clean way for doing this job.
The Array.prototype.some() method tests whether at least one element in the array passes the test implemented by the provided function (in your case, falsy value).
const userData = {};
userData.firstName = "dd";
userData.lastName = false;
userData.email = 0;
userData.phone = 123;
userData.address = "aad";
userData.mailAddress = "dff";
const detailsConditionsArr = [
userData.firstName,
userData.lastName,
userData.email,
userData.phone,
userData.address,
userData.mailAddress,
]
const detailsConditionsArr2 = [true, 1, "fff"];
const doesHaveFalsy = obj => obj.some(x => !x);
if (doesHaveFalsy(detailsConditionsArr)) {
console.log("detailsConditionsArr Found a falsy");
}
if (doesHaveFalsy(detailsConditionsArr2)) {
console.log("detailsConditionsArr2 Found a falsy");
}
More about some - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

How to find a value in an array of objects?

I have an array of objects like this:
var data = [
{id:1,first_name:'John',last_name:'Doe',age:20,birth:'1992-01-12'},
{id:2,first_name:'Blaan',last_name:'Adey',age:35,birth:'2001-04-16'}
];
var searchColumn = ['first_name','last_name','birth'];
These values(searchColumn) ​​may change and not be constant.
For this reason they must be read from the array
I want to do this now :
function searchData(Val){
var newData = [];
if (Val){
for (let i=0 ; i < data.length ; i++){
searchColumn.forEach(value => {
if (data[i][value].includes(Val)){
newData.push(data[i]);
}
}
}
}
}
searchData('L');
please guide me.
This should do.
You don't have to loop through the array, you can use build-in functions like map, some and filter to achieve this.
var data = [
{id:1,first_name:'John',last_name:'Doe',age:20,birth:'1992-01-12'},
{id:1,first_name:'John',last_name:'Bal',age:20,birth:'1992-01-12'},
{id:2,first_name:'Blaan',last_name:'Adey',age:35,birth:'2001-04-16'}
];
var searchColumn = ['first_name','last_name','birth'];
var search = (searchParam) => {
// map here applies the function (value) => searchColumn.some(property => value[property] === searchParam) ? value : null
// over every value in the array & some loops through every value in the search column
// looking for an object where one of the properties specified in searchColumn has a value that matches our search parameter
return data.map(value => searchColumn.some(property => value[property] === searchParam) ? value : null)
.filter(result => !!result); // here we use filter to remove the null values mapped in the map function
}
search('John');
// result -> [{id:1,first_name:'John',last_name:'Doe',age:20,birth:'1992-01-12'},
// -> {id:1,first_name:'John',last_name:'Bal',age:20,birth:'1992-01-12'}]
UPDATE: As suggested, an better solution:
var search = (searchParam) => {
return data.filter(value => !!searchColumn.some(property => value[property] === searchParam));
}
... a configurable, thus more generic, approach based on Array.prototype.filter and Function.prototype.bind ...
function doesItemMatchBoundPropertyValueAndSearch(item) {
const { keyList, search } = this;
return keyList.some(key => item[key].includes(search));
}
const sampleDataList = [
{id: 1, first_name: 'John', last_name: 'Doe', age: 20, birth: '1992-01-12'},
{id: 2, first_name: 'Blaan', last_name: 'Adey', age: 35, birth: '2001-04-16'},
];
const searchColumn = ['first_name', 'last_name', 'birth'];
console.log(
"search: 'L' :",
sampleDataList.filter(
doesItemMatchBoundPropertyValueAndSearch.bind({
keyList: searchColumn,
search: 'L',
})
)
);
console.log(
"search: 'o' :",
sampleDataList.filter(
doesItemMatchBoundPropertyValueAndSearch.bind({
keyList: searchColumn,
search: 'o',
})
)
);
console.log(
"search: 'n' :",
sampleDataList.filter(
doesItemMatchBoundPropertyValueAndSearch.bind({
keyList: searchColumn,
search: 'n',
})
)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Cannot access value of object property

I am looping though an object to retrieve some properties but for some reason I cannot access the value of a nested object property.
This is my looping function:
parseContacts = (contacts) => {
return contacts.map(contact => {
let parsedContact = {};
Object.keys(contact).forEach(key => {
if (key === 'givenName') {
parsedContact.firstName = contact[key];
} if (key === 'familyName') {
parsedContact.surname = contact[key];
} if (key === 'phoneNumbers') {
parsedContact.phoneNumber = contact[key][0].number;
}
})
return parsedContact;
})
}
firstName and surname work fine, but in the last if statement I get undefined. the property with key phoneNumbers it is an array of objects, and this is item 0 in the array:
{id: "302", label: "mobile", number: "+44 7X7X 50XX72"}
When I use this code instead:
} if (key === 'phoneNumbers') {
parsedContact.phoneNumber = contact[key][0];
}
without .number on the end I get the whole object back fine, I just can't get back only the number property from the object.
Update
On closer inspection, the array which has over 800 large objects in, some of the lengths of the phoneNumbers arrays were 0 so the property did not exist. This was causing the whole function to fail. Thanks for the comments below.
My solution was to add to the if statement:
if (key === 'phoneNumbers' && contact[key].length)
You can prevent the empty phoneNumbers array issue like this:
contact[key] && contact[key].length ? contact[key][0].number : ''
const parseContacts = contacts => {
return contacts.map(contact => {
let parsedContact = {}
Object.keys(contact).forEach(key => {
switch (key) {
case 'givenName':
parsedContact.firstName = contact[key]
break
case 'familyName':
parsedContact.surname = contact[key]
break
case 'phoneNumbers':
parsedContact.phoneNumber = contact[key] && contact[key].length ? contact[key][0].number : ''
}
})
return parsedContact
})
}
const contacts = []
for (let i = 0; i < 10; i++) {
contacts.push({
givenName: faker.name.firstName(),
familyName: faker.name.lastName(),
phoneNumbers: [
{
id: faker.random.uuid(),
label: 'mobile',
number: faker.phone.phoneNumber()
}, {
id: faker.random.uuid(),
label: 'mobile',
number: faker.phone.phoneNumber()
}
]
})
}
contacts.push({
givenName: faker.name.firstName(),
familyName: faker.name.lastName(),
phoneNumbers: []
})
contacts.push({
givenName: faker.name.firstName(),
familyName: faker.name.lastName(),
phoneNumbers: null
})
console.log('RESULT ' + JSON.stringify(parseContacts(contacts)))
<script src="https://rawgit.com/Marak/faker.js/master/examples/browser/js/faker.js"></script>

Select all from array where key: name is equal something

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/

Reordering array objects via javascript

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')

Categories

Resources