I have this JSON object:
{
"foo" : {
"58eedc4298d1712b870c8e0a" : false,
"58eedc4298d1712b870c8e06" : true,
"58eedc4198d1712b870c8e05" : true
},
"bar" : {
"58eedc4298d1712b870c8e0a" : "git",
"58eedc4298d1712b870c8e06" : "svn",
"58eedc4198d1712b870c8e05" : "hg"
},
}
I want to get an object that looks like:
{
git: false,
svn: true,
hg: true
}
every algorithm I have come up with is very verbose, anybody think of something quick and clever?
var newObj = {};
for (let property in obj.bar) {
if obj.bar.hasOwnProperty(property){
newObj[obj.bar[property]] = obj.foo[property];
}
}
I'm really not a js dev, but this is where I would start.
The code above is written without any kind of syntax checking. I have no idea if it will actually compile.
If you are using lodash (if not you should), you can do in following way.
var _ = require("lodash");
var data = {
"foo": {
"58eedc4298d1712b870c8e0a": false,
"58eedc4298d1712b870c8e06": true,
"58eedc4198d1712b870c8e05": true
},
"bar": {
"58eedc4298d1712b870c8e0a": "git",
"58eedc4298d1712b870c8e06": "svn",
"58eedc4198d1712b870c8e05": "hg",
"58eedc4198d1712b870c8e06": "fa"
},
}
var keys = _.keys(data.bar);
var result = {};
_.forEach(keys, function (key) {
result[data.bar[key]] = data.foo[key] ? data.foo[key] : false;
});
console.log(result);
Related
Hi,
I have this code:
var gameon = 1;
var fighter1 = {"userid":"97","username":"john","items":{},"ailments":{}};
var fighter2 = {"userid":"91","username":"james","items":{},"ailments":{}};
var resume = 30;
all = {gameon:gameon,fighter1:fighter1,fighter2:fighter2,resume:resume,inturn:fighter1,outturn:fighter2};
fs.writeFileSync(file, util.inspect(all, { showHidden: true, depth: null }), { encoding: 'utf8', flag: 'w' });
I expect to have the next output written to file:
{
"gameon":1,
"fighter1":{
"userid":"97",
"username":"john",
"items": {},
"ailments":{}
},
"fighter2":{
"userid":"91",
"username":"james",
"items":{},
"ailments":{}
},
"resume":"",
"inturn":{
"userid":"97",
"username":"john",
"items":{},
"ailments":{}
},
"outturn":{
"userid":"91",
"username":"james",
"items":{},
"ailments":{}
}
however, the keys are output without the quotes which will later result into errors when reading the JSON file back. Why is that? How can I customize it so it looks like my expected output?
Thank you.
I'm making a hybrid app and using WKWebView.
I need to pass a JavaScript Object to the emitter command to open the edit dialog.
Here is my code:
let statDict: [String: Any] = [
"income" : account.stat.income,
"expense" : account.stat.expense,
"summary" : account.stat.summary,
"incomeShorten" : account.stat.incomeShorten,
"expenseShorten" : account.stat.expenseShorten,
"summaryShorten": account.stat.summaryShorten
]
let accountDict: [String: Any] = [
"id": account.id,
"name": account.name,
"description": "",
"icon": account.icon,
"currency": account.currency,
"customer_contact_id": account.customer_contact_id ?? 0,
"is_archived": account.is_archived,
"sort": account.sort,
"create_datetime": account.create_datetime,
"update_datetime": account.update_datetime ?? "",
"stat": statDict
]
let accountData = try! JSONSerialization.data(withJSONObject: accountDict, options: JSONSerialization.WritingOptions(rawValue: 0))
guard let accountString = String(data: accountData, encoding: .utf8) else {
return
}
webView.evaluateJavaScript("function parse(string){ return JSON.parse(string)}") { result, error in
if error == nil { // this is returns correct staff
}
}
webView.evaluateJavaScript("parse('\(accountString)')") { object, error in
if error == nil {
let object = object as AnyObject
print("parse object \(object)")
webView.evaluateJavaScript("window.emitter.emit('openDialog', 'Account', \(object))") { (result, error) in
if error == nil { // here the error "Unexpected token '='..."
webView.evaluateJavaScript("window.emitter.on('closeDialog', function(){ window.webkit.messageHandlers.emitterMessage.postMessage('closeDialog'); })") { (result, error) in
if error == nil {
}
}
webView.evaluateJavaScript("window.emitter.on('createAccount', function(){ window.webkit.messageHandlers.emitterMessage.postMessage('createAccount'); })") { (result, error) in
if error == nil {
}
}
} else {
print(error as Any)
}
}
}
}
The \ (object) returned by the function looks like this:
{
"create_datetime" = "2021-08-24 19:19:28";
currency = RUB;
"customer_contact_id" = 1;
description = "";
icon = "";
id = 7;
"is_archived" = 0;
name = "Business 111";
sort = 0;
stat = {
expense = 0;
expenseShorten = 0;
income = 300000;
incomeShorten = 300K;
summary = 300000;
summaryShorten = 300K;
};
"update_datetime" = "";
}
but it should look like this:
{
create_datetime: "2021-08-24 19:19:28",
currency: "RUB",
customer_contact_id: 1,
description: "",
icon: "",
id: 7,
is_archived: false,
name: "Business 111",
sort: 0,
stat: {
expense: 0,
expenseShorten: "0",
income: 300000,
incomeShorten: "300K",
summary: 300000,
summaryShorten: "300K"
},
update_datetime: ""
}
With such an object, the compiler generates the error Unexpected token '='. Expected an identifier as property name.
The parse (string) function will return the correct object if you run it in the js compiler, but in swift the output is not correct.
How to bring an object to the correct form?
You are trying to pass the string interpolated representation of a Swift object (NSMutableDictionary in your case) to Javascript.
Instead you can directly pass the JSON representation to JS context since JSON is a native Javascript object it should do what you are trying to achieve :
/// Sample emitter function that consumes object an prints its local parameter, also assigns it to sample object value in window.
self.webView?.evaluateJavaScript(
"window.emitter = (sampleObject) => { window.sampleObject = sampleObject;setTimeout(function(){console.log('Hello sampleObject : ',sampleObject.name); }, 7000);}"
) { result, error in
if error == nil { // this is returns correct staff
}
}
self.webView?.evaluateJavaScript("window.emitter(\(accountString));") { result, error in
if error == nil {
print("parse object \(result)")
}
}
Result in window :
I have an array of objects and I want to extract the value when key is passes in 'filter' filter. Below is the controller code snippet I have tried, but the type of response I get is undefined. Please help me in finding where am I going wrong.
var states = [{"HIMACHAL PRADESH":"HP"},{"JAMMU AND KASHMIR":"JK"},{"JHARKHAND":"JH"},{"KARNATAKA":"KA"},{"KERALA":"KL"},{"MADHYA PRADESH":"MP"},{"MAHARASHTRA":"MH"},{"ORISSA":"OR"}]
var str = "ORISSA";
var abbr = $filter('filter')(states, {key: str}, true).value;
console.log ("ABBR:"+abbr);
P.S. I have injected $filter in the controller
Use Object.keys and find
var matchedState = states.find( s => Object.keys( s )[0] == str );
var abbr = matchedState ? matchedState[str] : ""
Demo
var states = [{
"HIMACHAL PRADESH": "HP"
}, {
"JAMMU AND KASHMIR": "JK"
}, {
"JHARKHAND": "JH"
}, {
"KARNATAKA": "KA"
}, {
"KERALA": "KL"
}, {
"MADHYA PRADESH": "MP"
}, {
"MAHARASHTRA": "MH"
}, {
"ORISSA": "OR"
}]
var str = "ORISSA";
var matchedState = states.find(s => Object.keys(s)[0] == str);
var abbr = matchedState ? matchedState[str] : ""
console.log(abbr);
Assuming a data structure like below, I want a rule that disallows adding new car makes, for example users cannot add "toyota". So, I need to .validate such that the .update must match an existing make.
I have tried using $cars with ".validate": "newData.val().contains($cars)" and all kind of other ways with no luck. Any help is appreciated.
My code is:
function setModel(model,make,key){
if (model && make && key){
var carsRef = ref.child('cars');
var makeRef = carsRef.child(make);
var modelRef = makeRef.child(model);
var obj = {};
obj[key] = true;
modelRef.update(obj, onComplete);
}
}
The firebase looks like:
{
"cars" : {
"chevrolet" : {
"silverado" : {
"id192874623" : true,
"id786766663" : true
}
},
"ford" : {
"taurus" : {
"id736273627" : true
}
},
"honda" : {
"accord" : {
"id635263535" : true
}
}
}}
To disallow adding new car brands:
"cars": {
"$brand": {
".validate": "data.exists()"
}
}
This is covered in the section on existing data vs new data of the documentation.
i have created a custom object that it's job is to give some more information on the data it holds...
so besides data, i have an object that is a base / "myObject" for all data i "deal" with, it will always carry its declaration name e.g Name, i also intend to have it categories itself (this is not my invention, that's kinda what namespaces are in .net c# where i feel more comfortable programming)
so this is the cause, ...some established form of common properties / values to all program data dealt with.
the problem is when it's within a collection /seq / set /array
i would like to be able to index it (in c# i heavily use indexers and enums)
where i could create an object and access it's data via it's a key.
//pName pVal (usually a data/json object could be anything)
var someRprop = Rprp("HomePhone" , { dtT: "string", dt: "0044-01...", cat "cusDat", division: "portal"; catId: 32})
function Rprp(parName, parVal) {
var cretdprp = {
pName:pPropName,
pVal: pVal,
pValAsint: parseInt(this.pVal)
};
return cretdprp;
}
now if i need to create an indexed by key collection i can't understand how i could create a matching collection-object to be able to access it via the property name.
so for instance, in the main object properties of any program i create, i have one such as "datatypes" :
//btw it has "nice" combination of Parentheses
function ProgMan(){
var Core = {
// here is where it's get little complicated for my current level of javascript
DataTypes: [
{
DateTime : Rprp("DateTime", {LenType :shortName, mxL: 35, isNumeric: false//... etc})
}
],
DataNcnsts: { I32 : "int", str: "string", Dt : "DateTime" },
HelmFactory : { }
};
return Core;
}
Edit added context of usage
TabularsWHRM: function () {
var rtWH = {
DTNDataTypes: function () {
var rtarr = new Array();
rtarr =[ Rprp("DateTime", {dateTime: this.DbLengts.pVal.vals.NameShort}),Rprp("int32", {Int32 : this.DbLengts.pVal.vals.NameShort }), Rprp("bool", { Boolean : this.DbLengts.pVal.vals.NameShort }), Rprp("objct", { Object: undefined }), Rprp("csvString", { CsvString: this.DbLengts.pVal.vals.csvString }), Rprp("string", { String: this.DbLengts.pVal.vals.string }), Rprp("Json", { Json: undefined }), Rprp("FileObj", { File: this.DbLengts.pVal.vals.NameShort })];
var tk = rtarr["DateTime"];
console.log("MyNamedkey >" + key.pName + " has Length value " + rtarr[key].pVal);
for (var key in rtarr) {
console.log("key " + key.pName + " has value " + rtarr[key].pVal.dateTime);
if (key == this.DTNDataTypes.dateTime) {
//dateTime: "DateTime", int32: "Int32", bool : "Boolean", objct: "Object",csvString: "CsvString", string : "String", Json: "Json", aFileObj: "File"}
}
}
return rtarr;
},
DbLengts: Rprp ("DbLengts",
{
vals : {
NameShort: 25,
Name: 50, NameLong: 150,
PathIO: 450, ShortDesc: 150, Desc: 450,
CommentsL1: 1000, CommentsL2: 2000, Text: 4000
,generate: function (pDTNDataTypes){
var s = pDTNDataTypes;
var rtIval = -1;
switch (s) {
case this.names.nameShort : rtIval = this.NameShort;
case this.names.name: rtIval = this.Name;
case this.names.nameLong: rtIval = this.NameLong;
case this.names.pathIO: rtIval = this.PathIO;
case this.names.shortDesc: rtIval = this.ShortDesc;
case this.names.desc: rtIval = this.Desc;
case this.names.commentsL1: rtIval = this.CommentsL1;
case this.names.commentsL2: rtIval = this.CommentsL2;
case this.names.text: rtIval = this.Text;
default: rtIval = 800;
break;
}
return parseInt(rtIval);
}
},
names :
{
nameShort : "NameShort", name : "Name", nameLong : "NameLong", pathIO : "PathIO", shortDesc : "ShortDesc", desc : "Desc", commentsL1 : "CommentsL1", commentsL2 : "CommentsL2", text : "Text"
}
})
};
return rtWH;
},