I want to make a for loop to check my class attributes, but I don't want to show those attributes what are undefined.
I have tried parse JSON with stringify and for each loop. But I've got the wrong generation.
for(var alma in Category){
if(typeof this.CatGroup !== "undefined"){
return ( "Type=" +
'"' +
this.Type
Object.keys(obj).forEach(function (key) {
if(typeof obj[key] === 'undefined'){
delete obj[key];
}
});
<C undefined/>
With this for loop, I got only undefined.
Here is one way to go about it:
const json = {
prop1: 'value1',
prop2: 'value2',
prop3: undefined,
}
console.log(
Object.entries(json)
.filter(([key, value]) => value !== undefined)
.map(([key, value]) => `${key}=${value}`)
.join(', ')
)
Related
I am receiving a data object from an api where some of its properties may have a value of null. I want to create a function that returns the object but for the properties that have a null value there is a "-" instead. I have tried:
const hyphenOrContent = movie => {
return Object.values(movie).map(val => {
return val === null ? "-" : val
});
}
but this only returns an array of the values. I've read that it's better not to use a for in loop so I would like to avoid using one if possible. Any help appreciated!
Map the object's entries, turning nulls into -s, then use Object.fromEntries to turn the array of entries into an object:
const hyphenOrContent = movie => Object.fromEntries(
Object.entries(movie).map(
([key, val]) => ([key, val === null ? "-" : val])
)
);
Just loop over the Object and alter the properties.
const hyphenOrContent = movie => {
Object.entries(movie).forEach(([key, val]) => {
if (val === null) movie[key] = '-';
});
};
var a = {
foo: null,
bar: '123',
baz: null
}
hyphenOrContent(a);
console.log(a);
If you do not want to alter the original, you can clone it.
I'm trying to replace all instances of a character in an object properties values
I'm stuck here. I can't figure out how to modify the value.
for(let [key, val] in obj){
if(typeof val === "string"){
???? = val.replace(/,/g, '')
}
}
You can't use destructuring to iterate over an object's properties and values with for-in.
And in order to replace the value, you have to use an object accessor, you can't replace with destructuring.
for (let key in obj) {
if (typeof obj[key] == "string") {
obj[key] = obj[key].replace(/,/g, '');
}
}
You can use Object.keys
Object.keys(obj).forEach((key) => (obj[key] = obj[key].replace("A", "n")));
Using Object.entries() and Array.prototype.forEach()
const obj = { a1: "aaaa,11,aa", b2: "bbbb,22,bb"};
Object.entries(obj).forEach(([key, val]) => obj[key] = val.replace(/,/g, ""));
console.log(obj)
In the given object all values of properties are the same.
var obj = {
property1: 'Some Value',
property2: 'Some Value',
property3: 'Some Value',
property4: 'Some Value'
}
The function checkEquality should return true if all values are the same and false otherwise.
I can do the following to achieve it:
function checkEquality () {
var compare = obj.propery1;
for (var key in obj) {
if (obj[key] !== compare) {
return false;
}
}
return true;
}
But this solution by far not the best.
You could use Array#every for it.
The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value (a value that becomes false when converted to a Boolean). If such an element is found, the every method immediately returns false. Otherwise, if callback returned a true value for all elements, every will return true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
var obj = { propery1: 'Some Value', propery2: 'Some Value', propery3: 'Some Value', propery4: 'Some Value' },
equal = Object.keys(obj).every(function (k, i, kk) {
return !i || obj[kk[0]] === obj[k];
});
console.log(equal);
Great answer by #Nina, I'd just like to add something different using reduce and ES6 syntax:
const sameValues = (obj ) => {
let keys = Object.keys( obj );
let initial = obj[ keys[0] ];
// val will be either the initial value or false
let val = keys.reduce( (prev, cur) => ( obj[cur] === prev ? prev : false ), initial );
return val === initial;
}
https://jsfiddle.net/9tb5mdoL/
I have a parse method in a backbone app that builds a JSON object out of an array, however if a value is empty, it is written as undefined, which breaks the behavior of other methods, I need to set undefined values as empty strings and am having trouble doing that, any help is greatly appreciated.
Note: in this case I am trying to set the value of value: to an empty string if obj[key] = undefined
code:
parse: function(data){
return data.map(function(obj){
var key = Object.keys(obj)[0];
return {
attribute: key,
value: obj[key]
};
});
}
toQueryString: function(){
var obj = this.toQueryData(),
qs = [];
for (key in obj) {
qs.push(key + "=" + obj[key]);
}
return qs.join('&')
},
toQueryData: function(){
return this.reduce(function(memo, model){
memo[model.get('attribute')] = model.get('value');
return memo
}, {});
}
Use a ternary condition:
value: obj[key] ? obj[key] : ""
Or (as pointed out by #Derek朕會功夫),
value: obj[key] || ""
You need to check if the object has the property - key.
value: obj.hasOwnProperty(key) && obj[key] != undefined ? obj[key] : ""
// or you could write it like this (which I prefer, think the bracket syntax is a little bit uglier):
value: obj.hasOwnProperty(key) && obj.key != undefined ? obj.key : ""
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
Since your using backbone you could use underscores defaults method:
return _.defaults({attribute: key, value: obj[key]}, {value: ''});
toQueryString: function(){
var obj = this.toQueryData(),
qs = [];
for (key in obj) {
qs.push(key + "=" + (obj.hasOwnProperty(key) && obj.key != undefined ? obj.key : ""));
}
return qs.join('&')
}
This ended up being the solution, thanks Marko!
This question already has answers here:
Remove blank attributes from an Object in Javascript
(53 answers)
Closed 5 years ago.
Is there a clean way to remove undefined fields from an object?
i.e.
> var obj = { a: 1, b: undefined, c: 3 }
> removeUndefined(obj)
{ a: 1, c: 3 }
I came across two solutions:
_.each(query, function removeUndefined(value, key) {
if (_.isUndefined(value)) {
delete query[key];
}
});
or:
_.omit(obj, _.filter(_.keys(obj), function(key) { return _.isUndefined(obj[key]) }))
A one-liner using ES6 arrow function and ternary operator:
Object.keys(obj).forEach(key => obj[key] === undefined ? delete obj[key] : {});
Or use short-circuit evaluation instead of ternary: (#Matt Langlois, thanks for the info!)
Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key])
Same example using if statement:
Object.keys(obj).forEach(key => {
if (obj[key] === undefined) {
delete obj[key];
}
});
If you want to remove the items from nested objects as well, you can use a recursive function:
const removeEmpty = (obj) => {
let newObj = {};
Object.keys(obj).forEach((key) => {
if (obj[key] === Object(obj[key])) newObj[key] = removeEmpty(obj[key]);
else if (obj[key] !== undefined) newObj[key] = obj[key];
});
return newObj;
};
I prefer to use something like Lodash:
import { pickBy, identity } from 'lodash'
const cleanedObject = pickBy(originalObject, identity)
Note that the identity function is just x => x and its result will be false for all falsy values. So this removes undefined, "", 0, null, ...
If you only want the undefined values removed you can do this:
const cleanedObject = pickBy(originalObject, v => v !== undefined)
It gives you a new object, which is usually preferable over mutating the original object like some of the other answers suggest.
Use JSON Utilities
Overview
Given an object like:
var obj = { a: 1, b: undefined, c: 3 }
To remove undefined props in an object we can use nested JSON methods stringify and parse like so:
JSON.parse(JSON.stringify(obj))
Live Example
var obj = { a: 1, b: undefined, c: 3 }
var output = JSON.parse(JSON.stringify(obj));
console.log(output)
Limitations and warnings
Depending on how Javascript is implemented.
It is possible that undefined will be converted to null instead of just being removed.
Nested Object, Array will be converted to strings
Date, time values also converted to strings
Tested
The above code was tested in Firefox, Chrome, and Node 14.18.1 and removed "b" from all obj arrays. Still I recommend exercising caution using this method unless you are in a stable environment (such as cloud functions or docker) I would not rely on this method client side.
Because it doesn't seem to have been mentioned, here's my preferred method, sans side effects or external dependencies:
const obj = {
a: 1,
b: undefined
}
const newObject = Object.keys(obj).reduce((acc, key) => {
const _acc = acc;
if (obj[key] !== undefined) _acc[key] = obj[key];
return _acc;
}, {})
console.log(newObject)
// Object {a: 1}
This solution also avoids hasOwnProperty() as Object.keys returns an array of a given object's own enumerable properties.
Object.keys(obj).forEach(function (key) {
if(typeof obj[key] === 'undefined'){
delete obj[key];
}
});
and you can add this as null or '' for stricter cleaning.
Here's a plain javascript (no library required) solution:
function removeUndefinedProps(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && obj[prop] === undefined) {
delete obj[prop];
}
}
}
Working demo: http://jsfiddle.net/jfriend00/djj5g5fu/
Mhh.. I think #Damian asks for remove undefined field (property) from an JS object.
Then, I would simply do :
for (const i in myObj) {
if (typeof myObj[i] === 'undefined') {
delete myObj[i];
}
}
Short and efficient solution, in (vanilla) JS !
Example :
const myObj = {
a: 1,
b: undefined,
c: null,
d: 'hello world'
};
for (const i in myObj) {
if (typeof myObj[i] === 'undefined') {
delete myObj[i];
}
}
console.log(myObj);
This one is easy to remember, but might be slow. Use jQuery to copy non-null properties to an empty object. No deep copy unless you add true as first argument.
myObj = $.extend({}, myObj);
Another Javascript Solution
for(var i=0,keys = Object.keys(obj),len=keys.length;i<len;i++){
if(typeof obj[keys[i]] === 'undefined'){
delete obj[keys[i]];
}
}
No additional hasOwnProperty check is required as Object.keys does not look up the prototype chain and returns only the properties of obj.
DEMO