Related
I am trying to get the "path" of an AngularJS scope variable and not having much luck. I want to eventually pass that "path" to be used as the ng-model of some dynamic forms that are being created.
Here is my code so far:
my_code.js:
var my_data = {
name: "fred",
number: 1,
children: [
{ name: "bob" },
{ name: "joe" },
{ name: "norman" },
]
};
function get_path(obj, target, path) {
if (typeof path === "undefined" || path === null) {
path = "my_data";
}
for (var key in obj) {
var value = obj[key];
var value_type = value.constructor;
/* value can either be an Array */
if (value_type === Array) {
for (var i=0; i<value.length; i++) {
if (value[i] === target) {
return path + "." + key + "[" + i + "]";
}
var result = get_path(value, target, path + "." + key + "[" + i + "]");
if (result) {
return result;
}
}
}
/* or an Object (dictionary) itself */
else if (value_type === Object) {
var result = get_path(value, target, path + "." + key);
if (result) {
return result;
}
}
/* or something atomic (string, number, etc.) */
else {
if (value === target) {
return path + "." + key;
}
}
}
return false;
}
If I pass the object my_data.children[0].name to this function, I would expect it to return the string "my_data.children[0].name". But it is actually returning "my_data.children[0].0.name". Any ideas on where I'm going wrong?
P.S. - I got the initial idea from Javascript/JSON get path to given subnode?, but that didn't handle Arrays.
I think your error is at :
else if (value_type === Object) {
var result = get_path(value, target, path + "." + key);
if (result) {
return result;
}
}
you have added "." + key. just remove it become like below:
else if (value_type === Object) {
var result = get_path(value, target, path );
if (result) {
return result;
}
}
#min-hong-tan solved the problem, and should be the accepted answer. But for completeness sake, I added the following lines:
if (value === target) {
return path + "." + key;
}
after each if block just in case I was trying to match an entire Array (as with my_data.children) or an entire Object that is not part of an Array.
I would like to list all paths of object that lead to leafs
Example:
var obj = {
a:"1",
b:{
foo:"2",
bar:3
},
c:[0,1]
}
Result:
"a","b.foo","b.bar", "c[0]","c[1]"
I would like to find simple and readable solution, best using lodash.
Here is a solution that uses lodash in as many ways as I can think of:
function paths(obj, parentKey) {
var result;
if (_.isArray(obj)) {
var idx = 0;
result = _.flatMap(obj, function (obj) {
return paths(obj, (parentKey || '') + '[' + idx++ + ']');
});
}
else if (_.isPlainObject(obj)) {
result = _.flatMap(_.keys(obj), function (key) {
return _.map(paths(obj[key], key), function (subkey) {
return (parentKey ? parentKey + '.' : '') + subkey;
});
});
}
else {
result = [];
}
return _.concat(result, parentKey || []);
}
Edit: If you truly want just the leaves, just return result in the last line.
Doesn't use lodash, but here it is with recursion:
var getLeaves = function(tree) {
var leaves = [];
var walk = function(obj,path){
path = path || "";
for(var n in obj){
if (obj.hasOwnProperty(n)) {
if(typeof obj[n] === "object" || obj[n] instanceof Array) {
walk(obj[n],path + "." + n);
} else {
leaves.push(path + "." + n);
}
}
}
}
walk(tree,"tree");
return leaves;
}
Based on Nick answer, here is a TS / ES6 imports version of the same code
import {isArray,flatMap,map,keys,isPlainObject,concat} from "lodash";
// See https://stackoverflow.com/a/36490174/82609
export function paths(obj: any, parentKey?: string): string[] {
var result: string[];
if (isArray(obj)) {
var idx = 0;
result = flatMap(obj, function(obj: any) {
return paths(obj, (parentKey || '') + '[' + idx++ + ']');
});
} else if (isPlainObject(obj)) {
result = flatMap(keys(obj), function(key) {
return map(paths(obj[key], key), function(subkey) {
return (parentKey ? parentKey + '.' : '') + subkey;
});
});
} else {
result = [];
}
return concat(result, parentKey || []);
}
Feeding that object through this function should do it I think.
recursePaths: function(obj){
var result = [];
//get keys for both arrays and objects
var keys = _.map(obj, function(value, index, collection){
return index;
});
//Iterate over keys
for (var key in keys) {
//Get paths for sub objects
if (typeof obj[key] === 'object'){
var paths = allPaths(obj[key]);
for (var path in paths){
result.push(key + "." + path);
}
} else {
result.push(key);
}
}
return result;
}
Here is my function. It generates all possible paths with dot notation, assuming there are no property names containing spaces
function getAllPathes(dataObj) {
const reducer = (aggregator, val, key) => {
let paths = [key];
if(_.isObject(val)) {
paths = _.reduce(val, reducer, []);
paths = _.map(paths, path => key + '.' + path);
}
aggregator.push(...paths);
return aggregator;
};
const arrayIndexRegEx = /\.(\d+)/gi;
let paths = _.reduce(dataObj, reducer, []);
paths = _.map(paths, path => path.replace(arrayIndexRegEx, '[$1]'));
return paths;
}
Here's my solution. I only did it because I felt the other solutions used too much logic. Mine does not use lodash since I don't think it would add any value. It also doesn't make array keys look like [0].
const getAllPaths = (() => {
function iterate(path,current,[key,value]){
const currentPath = [...path,key];
if(typeof value === 'object' && value != null){
return [
...current,
...iterateObject(value,currentPath)
];
}
else {
return [
...current,
currentPath.join('.')
];
}
}
function iterateObject(obj,path = []){
return Object.entries(obj).reduce(
iterate.bind(null,path),
[]
);
}
return iterateObject;
})();
If you need one where the keys are indexed using [] then use this:
const getAllPaths = (() => {
function iterate(path,isArray,current,[key,value]){
const currentPath = [...path];
if(isArray){
currentPath.push(`${currentPath.pop()}[${key}]`);
}
else {
currentPath.push(key);
}
if(typeof value === 'object' && value != null){
return [
...current,
...iterateObject(value,currentPath)
];
}
else {
return [
...current,
currentPath.join('.')
];
}
}
function iterateObject(obj,path = []){
return Object.entries(obj).reduce(
iterate.bind(null,path,Array.isArray(obj)),
[]
);
}
return iterateObject;
})();
const allEntries = (o, prefix = '', out = []) => {
if (_.isObject(o) || _.isArray(o)) Object.entries(o).forEach(([k, v]) => allEntries(v, prefix === '' ? k : `${prefix}.${k}`, out));
else out.push([prefix, o]);
return out;
};
Array are returned as .0 or .1 that are compatible with _.get of lodash
const getAllPaths = (obj: object) => {
function rKeys(o: object, path?: string) {
if (typeof o !== "object") return path;
return Object.keys(o).map((key) =>
rKeys(o[key], path ? [path, key].join(".") : key)
);
}
return rKeys(obj).toString().split(",").filter(Boolean) as string[];
};
const getAllPaths = (obj) => {
function rKeys(o, path) {
if (typeof o !== "object") return path;
return Object.keys(o).map((key) =>
rKeys(o[key], path ? [path, key].join(".") : key)
);
}
return rKeys(obj).toString().split(",").filter(Boolean);
};
const test = {
a: {
b: {
c: 1
},
d: 2
},
e: 1
}
console.log(getAllPaths(test))
I'm trying to create a JavaScript function that creates an object using strings for structure and fills it from DOM data.
For example, the following strings could look like this:
some.example.here = "hello"
some.example.there = "hi"
other.example = "heyo"
Which should create this object:
{
some: {
example: {
here: "hello",
there: "hi"
},
other: {
example: "heyo
}
}
The data as said comes from DOM and is being load at the code segment labeled "read data into object". The data loads fine and the object structure is being setup fine as well, but the data is not being put into the data field.
Here's the code for the function:
function getDataFromElement(element) {
obj = {};
$(element)
.find("[data-value]")
.each(function() {
// create object node
valueObj = {};
currentValueObj = valueObj;
$.each($(this).attr("data-value").split("."), function(i, objpath) {
currentValueObj[objpath] = {};
currentValueObj = currentValueObj[objpath];
});
// read data into object
if($(this).is("[data-putvalue]") && $(this).attr("data-putvalue") != "html") {
currentValueObj = $(this).attr($(this).attr("data-putvalue"));
} else {
currentValueObj = $(this).html();
}
console.log(currentValueObj);
// combine with previous gathered data
obj = $.extend(true, {}, obj, valueObj);
});
return obj;
}
Does anyone know what to do?
I would do it like this:
var createObject = function(model, name, value) {
var nameParts = name.split("."),
currentObject = model;
for (var i in nameParts) {
var part = nameParts[i];
if (i == nameParts.length-1) {
currentObject[part] = value;
break;
}
if (typeof currentObject[part] == "undefined") {
currentObject[part] = {};
}
currentObject = currentObject[part];
}
};
And then use it like that:
var model = {};
createObject(model, "some.example.here", "hello");
createObject(model, "some.example.there", "hi");
createObject(model, "other.example", "heyo");
Probably this can suit you (adapted from another project of mine, adapt and use as needed):
NOTE the element's name is taken as key and value as the value
function fields2model( $elements, dataModel )
{
$elements.each(function( ){
var $el = $(this),
name = $el.attr('name'),
key, k, i, o, val
;
key = name;
val = $el.val() || '';
k = key.split('.'); o = dataModel;
while ( k.length )
{
i = k.shift( );
if ( k.length )
{
if ( !o.hasOwnProperty( i ) ) o[ i ] = /^\d+$/.test( k[0] ) ? [ ] : { };
o = o[ i ];
}
else
{
o[ i ] = val;
}
}
});
}
Example use:
<input name="some.example.here" value="hello" />
<input name="some.example.there" value="hi" />
var model = {};
fields2model($('input,textarea,select'), model);
The example elements above will give the below model:
model = {
some: {
example: {
here: "hello",
there: "hi"
}
};
Some functional implementation:
const value = 'hello';
'some.example.here'.split('.').reverse().reduce((reduction, segment, index) => {
const result = {};
if (index === 0) {
result[segment] = value;
} else {
result[segment] = reduction;
}
return result;
}, {})
#theFreedomBanana +1
Works for me
const magicFunction = (string, value) =>
string
.split('.')
.reverse()
.reduce((acc, cur, index) => ({ [cur]: index === 0 ? value : acc }), {});
I need convert json object to url form like: "parameter=12&asd=1"
I done with this:
var data = {
'action':'actualiza_resultado',
'postID': 1,
'gl': 2,
'gl2' : 3
};
var string_=JSON.stringify(data);
string_=string_.replace(/{/g, "");
string_=string_.replace(/}/g, "");
string_=string_.replace(/:/g, "=")
string_=string_.replace(/,/g, "&");
string_=string_.replace(/"/g, "");
But i wonder if there any function in javascript or in JSON object to do this?
Use the URLSearchParams interface, which is built into browsers and Node.js starting with version 10, released in 2018.
const myParams = {'foo': 'hi there', 'bar': '???'};
const u = new URLSearchParams(myParams).toString();
console.log(u);
Old answer: jQuery provides param that does exactly that. If you don't use jquery, take at look at the source.
Basically, it goes like this:
url = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
}).join('&')
Using ES6 syntax:
var data = {
'action':'actualiza_resultado',
'postID': 1,
'gl': 2,
'gl2' : 3
};
let urlParameters = Object.entries(data).map(e => e.join('=')).join('&');
console.log(urlParameters);
I made an implementation that support nested objects and arrays i.e.
var data = {
users: [
{
"name": "jeff",
"tasks": [
"Do one thing",
"Do second thing"
]
},
{
"name": "rick",
"tasks": [
"Never gonna give you up",
"Never gonna let you down"
]
}
]
}
Will be:
users[0][name]=jeff&users[0][tasks][0]=Do%20one%20thing&users[0][tasks][1]=Do%20second%20thing&users[1][name]=rick&users[1][tasks][0]=Never%20gonna%20give%20you%20up&users[1][tasks][1]=Never%20gonna%20let%20you%20down
So, here's the implementation:
var isObj = function(a) {
if ((!!a) && (a.constructor === Object)) {
return true;
}
return false;
};
var _st = function(z, g) {
return "" + (g != "" ? "[" : "") + z + (g != "" ? "]" : "");
};
var fromObject = function(params, skipobjects, prefix) {
if (skipobjects === void 0) {
skipobjects = false;
}
if (prefix === void 0) {
prefix = "";
}
var result = "";
if (typeof(params) != "object") {
return prefix + "=" + encodeURIComponent(params) + "&";
}
for (var param in params) {
var c = "" + prefix + _st(param, prefix);
if (isObj(params[param]) && !skipobjects) {
result += fromObject(params[param], false, "" + c);
} else if (Array.isArray(params[param]) && !skipobjects) {
params[param].forEach(function(item, ind) {
result += fromObject(item, false, c + "[" + ind + "]");
});
} else {
result += c + "=" + encodeURIComponent(params[param]) + "&";
}
}
return result;
};
var data = {
users: [{
"name": "jeff",
"tasks": [
"Do one thing",
"Do second thing"
]
},
{
"name": "rick",
"tasks": [
"Never gonna give you up",
"Never gonna let you down"
]
}
]
}
document.write(fromObject(data));
You don't need to serialize this object literal.
Better approach is something like:
function getAsUriParameters(data) {
var url = '';
for (var prop in data) {
url += encodeURIComponent(prop) + '=' +
encodeURIComponent(data[prop]) + '&';
}
return url.substring(0, url.length - 1)
}
getAsUriParameters(data); //"action=actualiza_resultado&postID=1&gl=2&gl2=3"
Something I find nicely looking in ES6:
function urlfy(obj) {
return Object
.keys(obj)
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`)
.join('&');
}
Later update (same thing, maybe a bit cleaner):
const urlfy = obj => Object
.keys(obj)
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]))
.join('&');
Like #georg said, you can use JQuery.param for flat objects.
If you need to process complex objects, you can use JsonUri, a python package that does just that. There is JavaScript library for it as well
Disclaimer: I am the author of JSONURI
Edit: I learned much later that you can also just base64 encode your payload - most languages as support for base64 encoding/decoding
Example
x = {name: 'Petter', age: 47, places: ['Mozambique', 'Zimbabwe']}
stringRep = JSON.stringify(x)
encoded = window.btoa(stringRep)
Gives you eyJuYW1lIjoiUGV0dGVyIiwiYWdlIjo0NywicGxhY2VzIjpbIk1vemFtYmlxdWUiLCJaaW1iYWJ3ZSJdfQ==, which you can use as a uri parameter
decoded = window.atob(encoded)
originalX = JSON.parse(decoded)
Needless to say, it comes with its own caveats
But i wonder if there any function in javascript
Nothing prewritten in the core.
or json to do this?
JSON is a data format. It doesn't have functions at all.
This is a relatively trivial problem to solve though, at least for flat data structures.
Don't encode the objects as JSON, then:
function obj_to_query(obj) {
var parts = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
}
return "?" + parts.join('&');
}
alert(obj_to_query({
'action': 'actualiza_resultado',
'postID': 1,
'gl': 2,
'gl2': 3
}));
There isn't a standard way to encode complex data structures (e.g. with nested objects or arrays). It wouldn't be difficult to extend this to emulate the PHP method (of having square brackets in field names) or similar though.
This one processes arrays with by changing the nameinto mutiple name[]
function getAsUriParameters (data) {
return Object.keys(data).map(function (k) {
if (_.isArray(data[k])) {
var keyE = encodeURIComponent(k + '[]');
return data[k].map(function (subData) {
return keyE + '=' + encodeURIComponent(subData);
}).join('&');
} else {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
}
}).join('&');
};
Best solution for Vanilla JavaScript:
var params = Object.keys(data)
.filter(function (key) {
return data[key] ? true : false
})
.map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(data[key])
})
.join('&');
PS: The filter is used here to remove null or undefined parameters. It makes the url look cleaner.
The custom code above only handles flat data. And JQuery is not available in react native. So here is a js solution that does work with multi-level objects and arrays in react native.
function formurlencoded(data) {
const opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let sorted = Boolean(opts.sorted),
skipIndex = Boolean(opts.skipIndex),
ignorenull = Boolean(opts.ignorenull),
encode = function encode(value) {
return String(value).replace(/(?:[\0-\x1F"-&\+-\}\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g, encodeURIComponent).replace(/ /g, '+').replace(/[!'()~\*]/g, function (ch) {
return '%' + ch.charCodeAt().toString(16).slice(-2).toUpperCase();
});
},
keys = function keys(obj) {
const keyarr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Object.keys(obj);
return sorted ? keyarr.sort() : keyarr;
},
filterjoin = function filterjoin(arr) {
return arr.filter(function (e) {
return e;
}).join('&');
},
objnest = function objnest(name, obj) {
return filterjoin(keys(obj).map(function (key) {
return nest(name + '[' + key + ']', obj[key]);
}));
},
arrnest = function arrnest(name, arr) {
return arr.length ? filterjoin(arr.map(function (elem, index) {
return skipIndex ? nest(name + '[]', elem) : nest(name + '[' + index + ']', elem);
})) : encode(name + '[]');
},
nest = function nest(name, value) {
const type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : typeof value === 'undefined' ? 'undefined' : typeof(value);
let f = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
if (value === f) f = ignorenull ? f : encode(name) + '=' + f; else if (/string|number|boolean/.test(type)) f = encode(name) + '=' + encode(value); else if (Array.isArray(value)) f = arrnest(name, value); else if (type === 'object') f = objnest(name, value);
return f;
};
return data && filterjoin(keys(data).map(function (key) {
return nest(key, data[key]);
}));
}
The conversion from a JSON string to a URL query string can be done in a single line:
const json = '{"action":"actualiza_resultado","postID":1,"gl":2,"gl2":3}';
const queryString = new URLSearchParams(JSON.parse(json)).toString();
queryString would then be set to "action=actualiza_resultado&postID=1&gl=2&gl2=3".
Based on georg's answer, but also adding ? before the string and using ES6:
const query = !params ? '': Object.keys(params).map((k, idx) => {
let prefix = '';
if (idx === 0) {
prefix = '?';
}
return prefix + encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
}).join('&');
As most of the answers only convert flat objects to query parameters, I would like to share mine.
This function can handle flat objects, as well as nested arrays/objects while only using plain JS.
function incapsulateInBrackets(key)
{
return '[' + key + ']';
}
function encode(object, isSubEncode=false, prefix = '')
{
let parts = Object.keys(object).map( (key) => {
let encodedParts = [];
if(Array.isArray(object[key]))
{
object[key].map(function(innerKey, index){
encodedParts.push( encode(object[key][index], true, prefix + key + incapsulateInBrackets(index)));
});
}
else if(object[key] instanceof Object)
{
Object.keys(object[key]).map( (innerKey) => {
if(Array.isArray(object[key][innerKey]))
{
encodedParts.push( encode(object[key][index], true, prefix + incapsulateInBrackets(key) + incapsulateInBrackets(innerKey)) );
}
else
{
encodedParts.push( prefix + incapsulateInBrackets(key) + incapsulateInBrackets(innerKey) + '=' + object[key][innerKey] );
}
});
}
else
{
if(isSubEncode)
{
encodedParts.push( prefix + incapsulateInBrackets(key) + '=' + object[key] );
}
else
{
encodedParts.push( key + '=' + object[key] );
}
}
return encodedParts.join('&');
});
return parts.join('&');
}
Make a utility if you have nodejs
const querystring = require('querystring')
export function makeQueryString(params): string {
return querystring.stringify(params)
}
import example
import { makeQueryString } from '~/utils'
example of use
makeQueryString({
...query,
page
})
Read the latest documentation here.
I'm working on formatting a URL for the Facebook Feed Dialog. There's so many parameters though. I want to have a function for these dialogs, something like:
function generateDialogUrl(dialog, params) {
base = "http://www.facebook.com/dialog/" + dialog + "?";
tail = [];
for (var p in params) {
if (params.hasOwnProperty(p)) {
tail.push(p + "=" + escape(params[p]));
}
}
return base + tail.join("&")
}
Oh wow... I think I just answered my own question. Is that right? Is escape() the correct function to use?
I'm stuck in the Lovers source code.
UPDATE: Since, we're using jQuery, I rewrote the method using jQuery.each. I also replaced escape() with encodeURIComponent() as suggested by #galambalazs & #T.J. Crowder. Thanks, guys!
var generateDialogUrl = function (dialog, params) {
base = "http://www.facebook.com/dialog/" + dialog + "?";
tail = [];
$.each(params, function(key, value) {
tail.push(key + "=" + encodeURIComponent(value));
})
return base + tail.join("&");
}
It's working!
Better yet, use encodeURIComponent instead. See this article comparing the two:
The escape() method does not encode
the + character which is interpreted
as a space on the server side as well
as generated by forms with spaces in
their fields. Due to this shortcoming
and the fact that this function fails
to handle non-ASCII characters
correctly, you should avoid use of
escape() whenever possible. The best
alternative is usually
encodeURIComponent().
escape() will not encode: #*/+
There is a jQuery method to accomplish this: $.param. It would work like this:
var generateDialogUrl = function (dialog, params) {
base = 'http://www.facebook.com/dialog/' + dialog + '?';
return base + $.param(params);
}
const createQueryParams = (param, prefix = '') => {
let queryString = '';
if (param.constructor === Object) {
queryString = Object.keys(param).reduce((result, key) => {
const obj = param[key];
const queryParam = result ? `${result}&${prefix}` : prefix;
if (obj.constructor === Object) {
return `${queryParam}${createQueryParams(obj, `${key}.`)}`;
} else if(obj.constructor === Array) {
const qp= obj.map((item, index)=> {
if (item.constructor === Object || item.constructor === Array) {
const query = createQueryParams(item, `${key}[${index}].`);
return `${query}`;
} else {
return `${key}[${index}]=${item}`;
}
}).reduce((res, cur) => {
return res ? `${res}&${cur}`: `${cur}`;
}, '');
return `${queryParam}${qp}`;
} else {
return `${queryParam}${key}=${obj}`;
}
}, '');
} else if(param.constructor === Array) {
queryString = param.reduce((res, cur) => `${res},${cur}`);
} else {
queryString = param;
}
return encodeURI(queryString);
};
Example:
createQueryParams({"Context":{"countryCode":"NO"},"Pagination":{"limit":10,"offset":1},"AdditionalField":[{"name":"Policy Number","value":"Pol123"},{"name":"Policy Version","value":"PV1"}]});
convertJsonToQueryString: function (json, prefix) {
//convertJsonToQueryString({ Name: 1, Children: [{ Age: 1 }, { Age: 2, Hoobbie: "eat" }], Info: { Age: 1, Height: 80 } })
if (!json) return null;
var str = "";
for (var key in json) {
var val = json[key];
if (isJson(val)) {
str += convertJsonToQueryString(val, ((prefix || key) + "."));
} else if (typeof (val) == "object" && ("length" in val)) {
for (var i = 0; i < val.length; i++) {
//debugger
str += convertJsonToQueryString(val[i], ((prefix || key) + "[" + i + "]."));
}
}
else {
str += "&" + ((prefix || "") + key) + "=" + val;
}
}
return str ? str.substring(1) : str;
}
isJson = function (obj) {
return typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
};
example:
convertJsonToQueryString({Name:1,Children:[{Age:1},{Age:2,Hoobbie:"eat"}],Info:{Age:1,Height:80}})
Result:
"Name=1Children[0].Age=1Children[1].Age=2&Children[1].Hoobbie=eatInfo.Age=1&Info.Height=80"