Adding single quotes to values in object (javascript) - javascript

I have a string like this :
"[ {name: foo, type: int}, {name: status, type: string},
{name: boo, type: string}, {name: koo, type: data} ]"
and i need to add single quotes for values inside every object , to become like this string :
"[ {name: 'foo', type: 'int'}, {name: 'status', type:
'string'}, {name: 'boo', type: 'string'}, {name: 'koo',
type: 'data'} ]"
i have tried to use eval , JSON.parse , but didn't see the expected result , is there any idea to do this and just add the single quotes for values in objects ?
This is the whole JSON , but i only need the fields part .
{
"success": true,
"count": 1,
"data": [
{
"res": "extend: 'someCode', fields: [ {name: foo, type: int},
{name: status, type: string},
{name: boo, type: string}, {name: koo, type: data} ]"
}
]
}

Here's a way to do it with a regex:
const val = `[ {name: foo, type: int}, {name: status, type: string},
{name: boo, type: string}, {name: koo, type: data} ]`
console.log(val.replace(/(\w+)\s*\:\s*(\w+)/g, "$1: '$2'"))
Seems to produce a valid javascript array:
> eval(val.replace(/(\w+)\s*\:\s*(\w+)/g, "$1: '$2'"))
[ { name: 'foo', type: 'int' },
{ name: 'status', type: 'string' },
{ name: 'boo', type: 'string' },
{ name: 'koo', type: 'data' } ]
Might have to tweak it to suit your use case.

Here are the tweaks needed to fix Richard's code
let val = `[ {name: foo, type: int}, {name: status, type: string}, {name: boo, type: string}, {name: koo, type: data} ]`
val = val.replace(/(\w+)\s*\:\s*(\w+)/g, "\"$1\": \"$2\"")
console.log(JSON.parse(val))
Here is a correct JS object from the "JSON" you posted
{
"success": "true",
"count": 1,
"data": [{
"res": { "extend": "someCode" },
"fields": [
{"name": "foo", "type": "int"},
{"name": "status", "type": "string"},
{"name": "boo", "type": "string"},
{"name": "koo", "type": "data" }
]
}
]
}

Regexp replacement may be easy for this.
var s = "[ {name: foo, type: int}, {name: status, type: string}, {name: boo, type: string}, {name: koo, type: data} ]";
console.log(s.replace(/:[ ]*([^ ,}]+)/gi, ": '$1'"));
> "[ {name: 'foo', type: 'int'}, {name: 'status', type: 'string'}, {name: 'boo', type: 'string'}, {name: 'koo', type: 'data'} ]"
Please see below too.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Related

How to exclude the null value in an object using every method in javascript

I am having a json object which is by default has 12 objects user can add value to the object.If the user adds value only for 2 objects and when i tried to use every() it returns false even though the condition which i have set as true because of the empty values in the object.
I would like to know how to exclude an object which has empty value.
vm.schemeApply.documents.filter(function(doc) {
$log.log("base64", base64MimeType(doc.url));
if (doc.url && doc.url.length > 0) {
return (
base64MimeType(doc.url) === ".png" ||
base64MimeType(doc.url) === ".pdf" ||
base64MimeType(doc.url) === ".jpeg"
);
}
});
Array Example:
[
{name: "Test1", url: "AADDfdfdfdfdfdfdfdfdf"},
{name: "Test2", url: "AADDfdfdfdfdfdfdfdfdf"},
{name: "Test3", url: ""},
{name: "Test4", url: ""},
{name: "Test5", url: ""},
{name: "Test6", url: ""},
{name: "Test7", url: ""},
{name: "Test8", url: ""},
{name: "Test9", url: ""},
{name: "Test10", url: ""}
]
You could use filter() casting the value of url to true or false using !! like newArr = arr.filter(o=>(!!o.url)):, or just:
const arr = [
{name: "Test1", url: "AADDfdfdfdfdfdfdfdfdf"},
{name: "Test2", url: "AADDfdfdfdfdfdfdfdfdf"},
{name: "Test3", url: ""},
{name: "Test4", url: ""},
{name: "Test5", url: ""},
{name: "Test6", url: ""},
{name: "Test7", url: ""},
{name: "Test8", url: ""},
{name: "Test9", url: ""},
{name: "Test10", url: ""}
]
newArr = arr.filter(o=>(o.url))
console.log(newArr)
every() is not useful for you in this situation I think, because returns true (or false) whether:
all elements in the array pass the test implemented by
the provided function.
this may be not the best solution but :
var returnValue = false;
vm.schemeApply.documents.filter(function(doc) {
$log.log("base64", base64MimeType(doc.url));
if (doc.url && doc.url.length > 0) {
let condition = ((base64MimeType(doc.url) === ".png") || (base64MimeType(doc.url) === ".pdf") || (base64MimeType(doc.url) === ".jpeg"));
if(condition) {
returnValue = true;
}
return condition;
}
return returnValue;
});
what i've done here is if only one object exist then the next object with empty url will return true
Looks like you're returning in the wrong spot. Your if statement receives a return, but you're never returning anything to the filter method. A slightly more terse example:
const docs = [
{name: "Test1", url: "123"},
{name: "Test2", url: "124"},
{name: "Test3", url: ""},
{name: "Test4", url: ""},
{name: "Test5", url: ""},
{name: "Test6", url: ""},
{name: "Test7", url: ""},
{name: "Test8", url: ""},
{name: "Test9", url: ""},
{name: "Test10", url: ""}
]
const result = docs.filter(function(doc) {
return !!doc.url && (
doc.url === '123' ||
doc.url === '124'
)
});
console.log(result)
Or, if you prefer using the if statement, you could also write it as:
const result = docs.filter(function(doc) {
const hasDoc = !!doc.url
let result
if (hasDoc) { result =
doc.url === '123' ||
doc.url === '124'
}
return result
})

How to group objects into one object in underscore

How to convert this :
[
{name: 'foo', type: 'product'},
{name: 'bar', type: 'product'},
{name: 'john', type: 'product'},
{name: 'no name', type: 'product'},
]
How can i group and get all the objects without name:'no name' as separate Object like this:
{
0:[
{name: 'foo', type: 'product'},
{name: 'bar', type: 'product'},
{name: 'john', type: 'product'}
],
1:[
{name: 'no name', type: 'product'},
]
}
To produce an object with keys 0 and 1, use _.groupBy:
var objectResult = _.groupBy(data, function(d) { return +(d.name === "no name") })
To produce an array with two elements (which will also have keys 0 and 1) you could use _.partition (Underscore 1.6.0 +):
partition_.partition(array, predicate): Split array into two arrays:
one whose elements all satisfy predicate and one whose elements all do
not satisfy predicate.
var arrayResult = _.partition(data, function(d) { return d.name !== "no name" })
JSBin
As a comparison, plain ECMAScript takes just a little more code:
data.reduce(function(acc, obj) {
acc[obj.name == 'no name'? 1:0].push(obj);
return acc;},{0:[],1:[]}
);
You can try http://underscorejs.org/#groupBy:
var data = [
{name: 'foo', type: 'product'},
{name: 'bar', type: 'product'},
{name: 'john', type: 'product'},
{name: 'no name', type: 'product'},
]
var results = _.groupBy(data, function(obj) { return obj.name == 'no name' ? 1 : 0; })
console.log(results)
You can try like that.
var arr = [
{name: 'foo', type: 'product'},
{name: 'bar', type: 'product'},
{name: 'john', type: 'product'},
{name: 'no name', type: 'product'},
];
var result = _.groupBy(arr, function (elem) {
return elem.name == 'no name' ? 1: 0;
});
Why use a framework for such a simple thing ?
Here is a pure JS solution allowing to groupBy properly.
It is then easy to work with the result object.
var array=[
{name: 'foo', type: 'product'},
{name: 'bar', type: 'product'},
{name: 'john', type: 'product'},
{name: 'no name', type: 'product'},
{name: 'foo', type: 'product'},
{name: 'bar', type: 'product'},
{name: 'john', type: 'product'},
{name: 'no name', type: 'product'},
{name: 'no name', type: 'product'},
{name: 'no name', type: 'product'},
{name: 'no name', type: 'product'},
];
function groupBy(propertyName, array) {
var groupedElements = {};
for (var i = 0, len = array.length; i < len; i++) {
var el = array[i];
var value = el[propertyName].trim();
var group = groupedElements[value];
if (group === undefined) {
group = [el];
groupedElements[value] = group;
} else {
group.push(el);
}
}
return groupedElements;
}
var result = groupBy('name',array);

EXTJS JsOnStore bit but display blank value

This is an Picture Show PowerOff Return value with \u0001 , but unfortunately when i store in JsOnStore are failure and i m trying to alert('PowerOff') are blank, why?
this is my JsOnStore Model Data
Ext.define('GoogleMarkerModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'ID', type: 'int'},
{name: 'Locating', type: 'int'},
{name: 'MainPower', type: 'int'},
{name: 'Acc', type: 'int'},
{name: 'PowerOff', type: 'int'}, // i have tried int,string,bit
{name: 'Alarm', type: 'int'},
{name: 'Speed', type: 'int'},
{name: 'Direction', type: 'int'},
{name: 'Latitude', type: 'float'},
{name: 'Longitude', type: 'float'},
{name: 'DateTime', type: 'datetime'},
{name: 'MainID', type: 'int'},
{name: 'IOState', type: 'int'},
{name: 'OilState', type: 'int'},
{name: 'PicUploadedDateTime', type: 'datetime'},
{name: 'PicData', type: 'str'}
]
});

How can I dynamically extend an object?

This is an example of data to use for a jquery library, however my data is dymanic and not hard coded.
var tree_data = {
'for-sale' : {name: 'For Sale', type: 'folder'} ,
'vehicles' : {name: 'Vehicles', type: 'folder'} ,
'rentals' : {name: 'Rentals', type: 'folder'} ,
'real-estate' : {name: 'Real Estate', type: 'folder'} ,
'pets' : {name: 'Pets', type: 'folder'} ,
'tickets' : {name: 'Tickets', type: 'item'} ,
'services' : {name: 'Services', type: 'item'} ,
'personals' : {name: 'Personals', type: 'item'}
}
So, My question is if I have this for example:
var tree_data = {
'for-sale' : {name: 'For Sale', type: 'folder'} ,
'vehicles' : {name: 'Vehicles', type: 'folder'}
}
How would I add
rentals' : {name: 'Rentals', type: 'folder'} ,
'real-estate' : {name: 'Real Estate', type: 'folder'}
To tree_data after its already created?
I also need to do this for this code, if you could possibly provide an example for both.
tree_data['for-sale']['additionalParameters'] = {
'children' : {
'appliances' : {name: 'Appliances', type: 'item'},
'arts-crafts' : {name: 'Arts & Crafts', type: 'item'},
'clothing' : {name: 'Clothing', type: 'item'},
'computers' : {name: 'Computers', type: 'item'},
'jewelry' : {name: 'Jewelry', type: 'item'},
'office-business' : {name: 'Office & Business', type: 'item'},
'sports-fitness' : {name: 'Sports & Fitness', type: 'item'}
}
}
If you're using jQuery.... try using $.extend()
http://api.jquery.com/jQuery.extend/
Otherwise...
var tree_data = {
'for-sale' : {name: 'For Sale', type: 'folder'} ,
'vehicles' : {name: 'Vehicles', type: 'folder'}
};
tree_data['rentals'] = {name: 'Rentals', type: 'folder'};
tree_data['real-estate'] = {name: 'Real Estate', type: 'folder'};

Extend from custom model class in ExtJS 4

How to extend from custom model in extjs.
Is there any method which can directly club the fields of User and BusinessUser fields when I'll refer the fields from BusinessUser class in example below.
Ext.define('User', {
extend: 'Ext.data.Model',
fields: [
{name: 'name', type: 'string'},
{name: 'age', type: 'int'},
{name: 'phone', type: 'string'},
{name: 'alive', type: 'boolean', defaultValue: true}
],
});
Ext.define('BusinessUser', {
extend: 'User',
fields: [
{name: 'businessType', type: 'string'},
{name: 'company', type: 'string'}
],
});
You don't need to join the fields manually because it's done automatically. Check the outputs in the code bellow based on your question:
Ext.define('User', {
extend: 'Ext.data.Model',
fields: [
{name: 'name', type: 'string'},
{name: 'age', type: 'int'},
{name: 'phone', type: 'string'},
{name: 'alive', type: 'boolean', defaultValue: true}
],
});
Ext.define('BusinessUser', {
extend: 'User',
fields: [
{name: 'businessType', type: 'string'},
{name: 'company', type: 'string'}
],
});
// instantiating a User object
var u = Ext.create('BusinessUser', {
name: 'John Doe',
age: 30,
phone: '555-5555'
});
// instantiating a BusinessUser object
var bu = Ext.create('BusinessUser', {
name: 'Jane Doe',
age: 40,
phone: '555-5556',
businessType: 'analyst',
company: 'ACME'
});
console.log(Ext.getClassName(bu)); // "BusinessUser"
console.log(Ext.getClassName(u)); // "User"
console.log(u instanceof User); // true
console.log(bu instanceof User); // true
console.log(u instanceof BusinessUser); // false
console.log(bu instanceof BusinessUser); // true
console.log(u instanceof Ext.data.Model); // true
console.log(bu instanceof Ext.data.Model); // true
console.log(u instanceof Ext.data.Store); // false, just to check if it's not returning true for anything
console.log(bu instanceof Ext.data.Store); // false
console.log("name" in u.data); // true
console.log("name" in bu.data); // true
console.log("company" in u.data); // false
console.log("company" in bu.data); // true
Although it should work automatically, use the below if you are having troubles for some reason.
Use the constructor to join the fields:
Ext.define('BusinessUser', {
extend : 'User',
constructor : function(){
this.callParent(arguments);
this.fields.push([
{name: 'businessType', type: 'string'},
{name: 'company', type: 'string'}
]);
}
});

Categories