So I'm trying to edit this rss feed with these 2 functions because of the media:content property which I have had no luck accessing directly. the functions I have below work for creating a new value called mediaContent which I can then easily access. The issue is in the rss feed not all objects will have media:content and I want to add a default value for the objects that don't have that property so I have consistency in my objects. Otherwise I end up with undefined on on some of mediaContent in my new object. I wanted to start just added a default value in when media:content is not present in the object but these ||'s are not working as I would have expected. How can I get my else if to punch in a default value if media:content does not exist? I'm probably missing something easy.
function getMediaContent(value) {
for (var i in value) {
if (i === "media:content") {
console.log("MC::", i)
return value[i].$;
} else if (i !== "title" || i !== "link" || i !== "pubDate" || i !== "isoDate" || i !== "guid" || i !== "contentSnippet" || i !== "content") {
debugger;
return "no media content"
}
}
}
function getNewsLinks() {
return newsItems.map(value => ({
value,
mediaContent: getMediaContent(value)
}))
}
SOLUTION (based on accepted answer)
function getMediaContent(value) {
return "media:content" in value ? value["media:content"].$ : "no media content";
}
works perfectly. Thanks!
Since you're just looking to see if a property exists on an object, you can use the in operator:
function getMediaContent(value) {
return "media:content" in value ? value["media:content"].$ : "no media content";
}
That checks if the property exists, and if so, gets the value of its $ property. Otherwise, returns the default value.
I needed something similar and optionally it would work for multi-layered JSON objects. Here is the function I use:
function getFromJSON(obj, ...args) {
for (const arg of args) {
if (!Array.isArray(arg)) {
if (arg in obj) {
obj = obj[arg]
} else {
return `${arg} not found in JSON`;
}
} else {
for (const argOpt of arg) {
if (argOpt in obj) {
obj = obj[argOpt]
break;
}
}
}
}
return obj
}
In addition, you can pass multiple keys in an array if you want to get the value of whichever exists.
I need to capture last focused input and paste something in it later.
I've already managed to catch last focused HTML input field (using jQuery on focusin event) or CKEDITOR editor (using CKEDITOR API on focus event). Because I store this last object in one var lastFocusedInput (jQuery object or CKEDITOR editor object), now I need to determine if it is CKEDITOR or jQuery object, due to they have different methods to paste data in it.
Any ideas how to do this in a more sophisticated way than testing it like that:
function isjQueryObject(o)
{
return (o && (o instanceof jQuery || o.constructor.prototype.jquery));
}
function isCKEditorObject(o)
{
return (o && (typeof CKEDITOR !== undefined) && (typeof o.insertHtml !== undefined));
}
EDIT on 2018-03-29
In the meantime I've ended up with type testing as below due to the need of reuse in other areas of the code.
function TypeTester()
{
var result = function (test)
{
return test ? true : false;
};
// jQuery [object Function]
this.jQuery = function (o)
{
return result(o
&& (o instanceof jQuery || o.constructor.prototype.jquery)
);
};
// CKEDITOR [object Object]
this.CKEDITOR =
{
object: function (o)
{
return result(o
&& o.replaceClass === 'ckeditor'
);
},
instance: function (o)
{
return result(o
&& o.insertHtml !== undefined
&& o.insertText !== undefined
);
},
};
};
var isTypeOf = new TypeTester();
var lastFocusedInput = new Object(
{
object: null,
insert: function (content)
{
if (!this.object) return;
switch (true)
{
case isTypeOf.jQuery(this.object) :
this.object.insertAtCaret(content);
break;
case isTypeOf.CKEDITOR.instance(this.object) :
this.object.insertHtml(content);
break;
}
},
});
As you know the typeof object while storing then store it like
var lastFocusedInput= { type:'jQuery', theObject: theObjectToStore};
And access it like so
if(lastFocusedInput.type == 'jQuery'){
//get jquery object -> lastFocusedInput.theObject
}else{
//get CKEDITOR object -> lastFocusedInput.theObject
}
Or use two containers
If object to store is jQuery
var $lastFocusedInput = theObjectToStore;
var CKElastFocusedInput= null;
or vice versa
while accessing
if($lastFocusedInput){// use jquery API on object }
else{ // use CKEDITOR API on object }
This question already has answers here:
How to set object property (of object property of..) given its string name in JavaScript?
(16 answers)
Closed 6 years ago.
I am trying to deeply assign a value in an object. For example:
const errors = {}
if(errorOnSpecificField) {
// TypeError: Cannot read property 'subSubCategory' of undefined(…)
errors.subCategory.subSubCategory.fieldWithError = 'Error Message'
}
Right now, without lodash, I can do:
const errors = {}
if(errorOnSpecificField) {
errors.subCategory = errors.SubCategory || {}
errors.subCategory.subSubCategory = errors.SubCategory.subSubCategory || {}
errors.subCategory.subSubCategory.fieldWithError = 'Error Message'
}
With lodash, I can do this:
const errors = {}
if(errorOnSpecificField) {
_.set(errors, 'subCategory.subSubCategory.fieldWithError', 'Error Message');
}
I am trying to avoid using a third party library. Is there a more elegant solution, especially now that es2015 has object destructuring. The inverse operation is easy:
let {subCategory : {subSubCategory: {fieldWithError}}} = errors
What is an elegant solution to deep object assignment? Thanks!
Here's a fairly readable way to safely assign to the deep object:
(((errors||{}).subCategory||{}).subSubCategory||{}).fieldWithError = 'Error Message'
That doesn't create errors.subCategory.subSubCategory if it doesn't already exist, though.
Short answer, no there is no clean way of doing this without writing a method for it (tbh you could just use the method from lodash without importing the whole library)
... however ...
WARNING This is for fun only. Do not try this in production (req es6).
Object.prototype.chainSet = function() {
let handler = {
get (target, name) {
if (!(name in target)) {
target[name] = new Proxy({}, handler)
}
return target[name]
}
}
return new Proxy(this, handler)
}
use:
let a = {}
a.chainSet().foo.bar.baz = 1
a.foo.bar.baz // => 1
Object.assign() will work just fine for what you're asking.
let errors = { otherField: "value" };
let newobj = {subCategory : {subSubCategory: {fieldWithError: "Error goes here"}}};
Object.assign(errors, newobj);
This yields:
{
otherField:'value',
subCategory: {
subSubCategory: {
fieldWithError:'Error goes here'
}
}
}
You could try something like below:
function ErrorRegistry(obj)
{
this.errors = obj || {};
this.addError = function(k, msg)
{
var keys = k.split('.');
var o = this.errors;
for(var i = 0, l = keys.length, last = l-1; i<l; i++)
{
if(typeof o[keys[i]] === 'undefined')
o[keys[i]] = {};
if(i == last)
o[keys[i]] = msg;
else
o = o[keys[i]];
}
};
}
var errors = {'subCategory1':{'fieldWithError1':'Error1'}};
var errorRegistry = new ErrorRegistry(errors);
errorRegistry.addError('subCategory1.fieldWithError2', "Error2");
errorRegistry.addError('subCategory1.subSubCategory1.fieldWithError3', "Error3");
errorRegistry.addError('subCategory1.subSubCategory2.fieldWithError4', "Error4");
errors = errorRegistry.errors;
console.log(errors);
If I have a JavaScript object:
var object = {
propertyOne: undefined,
propertyTwo: 'defined',
propertyThree: 'defined',
propertyFour: undefined
}
How can I create a method that will list the properties with undefined values (in the example's case, propertyOne and propertyFour).
I'm quite new to JavaScript, and this is what I had so far:
function getEmptyProperties(object) {
var emptyProps = [];
for (var property in object) {
if (object.property === undefined) {
emptyProps += property
}
}
return emptyProps
}
But this returns ALL of the properties, regardless if they are undefined or not.
I know I'm missing some things that are principal in JS, but can't figure it out. Kindly help please?
Iterate over the object with:
Object.keys(object).forEach(function(val, i){
if (object[val] === undefined){
//do things to save the properties you want to save or delete
}
})
For fundamentals I might suggest Eloquent JavaScript. It's free.
You have a number of syntax errors in your code that could be fixed if you read the first 6ish chapters.
var getEmptyProperties = function(object) {
var emptyProps = [];
for (var property in object) {
if (object[property] === undefined) {
emptyProps.push(property);
}
}
return emptyProps
}
You may use filter, to get an array of only the properties that are undefined:
var obj = {
propertyOne: undefined,
propertyTwo: 'defined',
propertyThree: 'defined',
propertyFour: undefined
};
var undefProps = Object.keys(obj).filter(function (key) {
return obj[key] === undefined;
});
// undefProps: ["propertyOne", "propertyFour"]
And with an arrow function!:
var undefProps = Object.keys(obj).filter(k => obj[k] === undefined);
I am looking for an efficient way to translate my Ember object to a json string, to use it in a websocket message below
/*
* Model
*/
App.node = Ember.Object.extend({
name: 'theName',
type: 'theType',
value: 'theValue',
})
The websocket method:
App.io.emit('node', {node: hash});
hash should be the json representation of the node. {name: thename, type: theType, ..}
There must be a fast onliner to do this.. I dont want to do it manualy since i have many attributes and they are likely to change..
As stated you can take inspiration from the ember-runtime/lib/core.js#inspect function to get the keys of an object, see http://jsfiddle.net/pangratz666/UUusD/
App.Jsonable = Ember.Mixin.create({
getJson: function() {
var v, ret = [];
for (var key in this) {
if (this.hasOwnProperty(key)) {
v = this[key];
if (v === 'toString') {
continue;
} // ignore useless items
if (Ember.typeOf(v) === 'function') {
continue;
}
ret.push(key);
}
}
return this.getProperties.apply(this, ret);
}
});
Note, since commit 1124005 - which is available in ember-latest.js and in the next release - you can pass the ret array directly to getProperties, so the return statement of the getJson function looks like this:
return this.getProperties(ret);
You can get a plain JS object (or hash) from an Ember.Object instance by calling getProperties() with a list of keys.
If you want it as a string, you can use JSON.stringify().
For example:
var obj = Ember.Object.create({firstName: 'Erik', lastName: 'Bryn', login: 'ebryn'}),
hash = obj.getProperties('firstName', 'lastName'), // => {firstName: 'Erik', lastName: 'Bryn'}
stringHash = JSON.stringify(hash); // => '{"firstName": "Erik", "lastName": "Bryn"}'
I have also been struggling with this. As Mirko says, if you pass the ember object to JSON.stringify you will get circular reference error. However if you store the object inside one property and use stringify on that object, it works, even nested subproperties.
var node = Ember.Object.create({
data: {
name: 'theName',
type: 'theType',
value: 'theValue'
}
});
console.log(JSON.stringify(node.get('data')));
However, this only works in Chrome, Safari and Firefox. In IE8 I get a stack overflow so this isn't a viable solution.
I have resorted to creating JSON schemas over my object models and written a recursive function to iterate over the objects using the properties in the schemas and then construct pure Javascript objects which I can then stringify and send to my server. I also use the schemas for validation so this solution works pretty well for me but if you have very large and dynamic data models this isn't possible. I'm also interested in simpler ways to accomplish this.
I modifed #pangratz solution slightly to make it handle nested hierarchies of Jsonables:
App.Jsonable = Ember.Mixin.create({
getJson: function() {
var v, json = {};
for (var key in this) {
if (this.hasOwnProperty(key)) {
v = this[key];
if (v === 'toString') {
continue;
}
if (Ember.typeOf(v) === 'function') {
continue;
}
if (App.Jsonable.detect(v))
v = v.getJson();
json[key] = v;
}
}
return json;
}
});
App.io.emit('node', {node: node.toJSON()});
Or if you have an ID property and want to include it:
App.io.emit('node', {node: node.toJSON({includeId: true})});
Will this work for you?
var json = JSON.stringify( Ember.getMeta( App.node, 'values') );
The false is optional, but would be more performant if you do not intend to modify any of the properties, which is the case according to your question. This works for me, but I am wary that Ember.meta is a private method and may work differently or not even be available in future releases. (Although, it isn't immediately clear to me if Ember.getMeta() is private). You can view it in its latest source form here:
https://github.com/emberjs/ember.js/blob/master/packages/ember-metal/lib/utils.js
The values property contains only 'normal' properties. You can collect any cached, computed properties from Ember.meta( App.node, false ).cached. So, provided you use jQuery with your build, you can easily merge these two objects like so:
$.extend( {}, Ember.getMeta(App.node, 'values'), Ember.getMeta(App.node, 'cache') );
Sadly, I haven't found a way to get sub-structures like array properties in this manner.
I've written an extensive article on how you can convert ember models into native objects or JSON which may help you or others :)
http://pixelchild.com.au/post/44614363941/how-to-convert-ember-objects-to-json
http://byronsalau.com/blog/convert-ember-objects-to-json/
I modified #Kevin-pauli solution to make it works with arrays as well:
App.Jsonable = Ember.Mixin.create({
getJson: function() {
var v, json = {}, inspectArray = function (aSome) {
if (Ember.typeof(aSome) === 'array') {
return aSome.map(inspectArray);
}
if (Jsonable.detect(aSome)) {
return aSome.getJson();
}
return aSome;
};
for (var key in this) {
if (this.hasOwnProperty(key)) {
v = this[key];
if (v === 'toString') {
continue;
}
if (Ember.typeOf(v) === 'function') {
continue;
}
if (Ember.typeOf(v) === 'array') {
v = v.map(inspectArray);
}
if (App.Jsonable.detect(v))
v = v.getJson();
json[key] = v;
}
}
return json;
}
});
I also made some further modification to get the best of both worlds. With the following version I check if the Jsonable object has a specific property that informs me on which of its properties should be serialized:
App.Jsonable = Ember.Mixin.create({
getJson: function() {
var v, json = {}, base, inspectArray = function (aSome) {
if (Ember.typeof(aSome) === 'array') {
return aSome.map(inspectArray);
}
if (Jsonable.detect(aSome)) {
return aSome.getJson();
}
return aSome;
};
if (!Ember.isNone(this.get('jsonProperties'))) {
// the object has a selective list of properties to inspect
base = this.getProperties(this.get('jsonProperties'));
} else {
// no list given: let's use all the properties
base = this;
}
for (var key in base) {
if (base.hasOwnProperty(key)) {
v = base[key];
if (v === 'toString') {
continue;
}
if (Ember.typeOf(v) === 'function') {
continue;
}
if (Ember.typeOf(v) === 'array') {
v = v.map(inspectArray);
}
if (App.Jsonable.detect(v))
v = v.getJson();
json[key] = v;
}
}
return json;
}
});
I am using this little tweak and I am happy with it. I hope it'll help others as well!
Thanks to #pangratz and #Kevin-Pauli for their solution!
Here I take #leo, #pangratz and #kevin-pauli solution a little step further. Now it iterates not only with arrays but also through has many relationships, it doesn't check if a value has the type Array but it calls the isArray function defined in Ember's API.
Coffeescript
App.Jsonable = Em.Mixin.create
getJson: ->
jsonValue = (attr) ->
return attr.map(jsonValue) if Em.isArray(attr)
return attr.getJson() if App.Jsonable.detect(attr)
attr
base =
if Em.isNone(#get('jsonProperties'))
# no list given: let's use all the properties
this
else
# the object has a selective list of properties to inspect
#getProperties(#get('jsonProperties'))
hash = {}
for own key, value of base
continue if value is 'toString' or Em.typeOf(value) is 'function'
json[key] = jsonValue(value)
json
Javascript
var hasProp = {}.hasOwnProperty;
App.Jsonable = Em.Mixin.create({
getJson: function() {
var base, hash, hashValue, key, value;
jsonValue = function(attr) {
if (Em.isArray(attr)) {
return attr.map(jsonValue);
}
if (App.Jsonable.detect(attr)) {
return attr.getJson();
}
return attr;
};
base = Em.isNone(this.get('jsonProperties')) ? this : this.getProperties(this.get('jsonProperties'));
json = {};
for (key in base) {
if (!hasProp.call(base, key)) continue;
value = base[key];
if (value === 'toString' || Em.typeOf(value) === 'function') {
continue;
}
json[key] = jsonValue(value);
}
return json;
}
});
Ember Data Model's object counts with a toJSON method which optionally receives an plain object with includeId property used to convert an Ember Data Model into a JSON with the properties of the model.
https://api.emberjs.com/ember-data/2.10/classes/DS.Model/methods/toJSON?anchor=toJSON
You can use it as follows:
const objects = models.map((model) => model.toJSON({ includeId: true }));
Hope it helps. Enjoy!
I have:
fixed and simplified code
added circular reference prevention
added use of get of value
removed all of the default properties of an empty component
//Modified by Shimon Doodkin
//Based on answers of: #leo, #pangratz, #kevin-pauli, #Klaus
//http://stackoverflow.com/questions/8669340
App.Jsonable = Em.Mixin.create({
getJson : function (keysToSkip, visited) {
//getJson() called with no arguments,
// they are to pass on values during recursion.
if (!keysToSkip)
keysToSkip = Object.keys(Ember.Component.create());
if (!visited)
visited = [];
visited.push(this);
var getIsFunction;
var jsonValue = function (attr, key, obj) {
if (Em.isArray(attr))
return attr.map(jsonValue);
if (App.Jsonable.detect(attr))
return attr.getJson(keysToSkip, visited);
return getIsFunction?obj.get(key):attr;
};
var base;
if (!Em.isNone(this.get('jsonProperties')))
base = this.getProperties(this.get('jsonProperties'));
else
base = this;
getIsFunction=Em.typeOf(base.get) === 'function';
var json = {};
var hasProp = Object.prototype.hasOwnProperty;
for (var key in base) {
if (!hasProp.call(base, key) || keysToSkip.indexOf(key) != -1)
continue;
var value = base[key];
// there are usual circular references
// on keys: ownerView, controller, context === base
if ( value === base ||
value === 'toString' ||
Em.typeOf(value) === 'function')
continue;
// optional, works also without this,
// the rule above if value === base covers the usual case
if (visited.indexOf(value) != -1)
continue;
json[key] = jsonValue(value, key, base);
}
visited.pop();
return json;
}
});
/*
example:
DeliveryInfoInput = Ember.Object.extend(App.Jsonable,{
jsonProperties: ["title","value","name"], //Optionally specify properties for json
title:"",
value:"",
input:false,
textarea:false,
size:22,
rows:"",
name:"",
hint:""
})
*/
Ember.js appears to have a JSON library available. I hopped into a console (Firebug) on one the Todos example and the following worked for me:
hash = { test:4 }
JSON.stringify(hash)
So you should be able to just change your line to
App.io.emit('node', { node:JSON.stringify(hash) })