I have a string in this format:
var x = "a=1; b=2; c=3; d=4"
and I would like to convert it to an object like this:
var y = {
a: "1",
b: "2",
c: "3",
d: "4"
}
Any ideas how to achieve that?
This works in iE9+
var x = "a=1; b=2; c=3; d=4",
y = {};
x.split(';').map(function (i) {
return i.split('=')
}).forEach(function (j) {
y[j[0].trim()] = j[1]
});
If you are using Node.js v4+
let x = "a=1; b=2; c=3; d=4",
y = {}
x.split(';').map(i => i.split('=')).forEach(j => y[j[0].trim()] = j[1])
You could try this (not bullet proof, refer to comments):
var json, str;
str = 'a=1; b=2; c=3; d=4';
str = str.replace(/\s*;\s*/g, ',');
str = str.replace(/([^,]+)=([^,]+)/g, '"$1":"$2"');
str = '{' + str + '}';
json = JSON.parse(str);
document.write(
'<pre>' + JSON.stringify(json) + '</pre>'
);
here is what i did and it seems to work fine:
var y = x.split(";");
var obj = {};
for(var i = 0; i < y.length ; i++){
var k = y[i].split("=");
var r = k[0].replace(" ", "");
obj[r] = k[1];
}
console.log(obj);
Related
Here is my code :
var doc = app.activeDocument;
var allLayers = new Array;
var allLayers = collectAllLayers(doc, allLayers);
function collectAllLayers (doc, allLayers){
for (var m = 0; m < doc.layers.length; m++){
var theLayer = doc.layers[m];
if (theLayer.typename === "ArtLayer"){
allLayers.push(theLayer);
}else{
collectAllLayers(theLayer, allLayers);
}
}
return allLayers;
}
alert("array_layers : " + allLayers);
I am getting in alert array like this
[Layer1],[Layer2],[Layer3];
and I want make it looks like this :
[Layer1,Layer2,Layer3];
Thanks for answers and help in advance!
The code in question already works correctly. Referring to the documentation on ArtLayer, you can prove this by printing some of the properties for each of the objects in the array:
function collectAllLayers (layerSet, layers){
for (var i = 0; i < layerSet.layers.length; i++){
var layer = layerSet.layers[i];
if (layer.typename === "ArtLayer"){
layers.push(layer);
} else {
collectAllLayers(layer, layers);
}
}
return layers;
}
function printable (artLayers) {
var layerDescriptions = [];
for (var i = 0; i < artLayers.length; i++) {
var layer = artLayers[i];
layerDescriptions.push(
'{ name: ' + layer.name +
', kind: ' + layer.kind +
', opacity: ' + layer.opacity +
', visible: ' + layer.visible +
' }'
);
}
return layerDescriptions;
}
var artLayers = collectAllLayers(app.activeDocument, []);
var layerDescriptions = printable(artLayers);
alert(layerDescriptions);
Code in the question do display single level array of ArtLayer objects. One can be confused, because toString method of ArtLayer object returns name of the layer in square brackets (in version of PS that I have installed (v19.1.5), "ArtLayer" string is displayed before layer name, but still inside square brackets). For example:
var doc = app.activeDocument;
alert(doc.layers[0]); // Alerts "[ArtLayer Layer 1]"
To flatten array ary you can use [].concat.apply([], ary), like in:
var ary = [1, ["A", "B", "C"], 3];
alert(ary[2]); // Alerts "3"
alert([].concat.apply([],ary)[2]); // Alerts "B"
How about using the allLayers.push(theLayer[0]); instead of allLayers.push(theLayer);.
Have you tried to flat the list in the recursive result?
var doc = app.activeDocument;
var allLayers = new Array;
var allLayers = collectAllLayers(doc, allLayers);
function collectAllLayers (doc, allLayers){
for (var m = 0; m < doc.layers.length; m++){
var theLayer = doc.layers[m];
if (theLayer.typename === "ArtLayer"){
allLayers.push(theLayer);
}else{
flatten(collectAllLayers(theLayer, allLayers));
}
}
return flatten(allLayers);
}
function flatten(arr) {return arr.reduce(
(a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
)};
alert("array_layers : " + allLayers);
you can use
const flatten = (layers, allLayers) => layers.reduce((acc,layer) => (Array.isArray(layer)) ? collectAllLayers(layer, acc) : acc.push(layer), allLayers);
const collectAllLayers = (doc, allLayers) => flatten(doc.layers, allLayers);
I have this string.
'"pen pineapple" apple pen "pen pen"'
Is there a good way to convert it into an object which would look like this:
{
a: "pen pineapple",
b: "apple",
c: "pen",
d: "pen pen"
}
I am looking for a solution in pure javascript!
Splitting strings that have quotes...
https://stackoverflow.com/a/18647776/2725684
Then converting that array into an object...
https://stackoverflow.com/a/4215753/2725684
So, when you combine these answers, it looks like this...
var myRegexp = /[^\s"]+|"([^"]*)"/gi;
var myString = '"pen pineapple" apple pen "pen pen"';
var myArray = [];
do {
var match = myRegexp.exec(myString);
if (match != null) {
myArray.push(match[1] ? match[1] : match[0]);
}
} while (match != null);
var obj = myArray.reduce(function(acc, cur, i) {
acc[i] = cur;
return acc;
}, {});
console.log(obj);
You could use an adapted version of Split a string by commas but ignore commas within double-quotes using Javascript and use Number#toString method for the keys.
var str = '"pen pineapple" apple pen "pen pen"',
arr = str.match(/(".*?"|[^" \s]+)(?=\s* |\s*$)/g),
object = {};
arr.forEach(function (a, i) {
object[(i + 10).toString(36)] = a.replace(/"/g, '');
})
console.log(object);
This might not be the most efficient function but does what you need (returns array)
function splitter(inputString) {
var splitted = inputString.split(' ');
var out = []
var temp = "";
var quoteStarted = false;
for (i = 0; i < splitted.length; i++) {
if (splitted[i].indexOf('"') > -1 && !quoteStarted) {
temp += splitted[i] + " ";
quoteStarted = true;
} else if (quoteStarted && splitted[i].indexOf('"') == -1) {
temp += splitted[i] + " ";
} else if (quoteStarted && splitted[i].indexOf('"') > -1) {
temp += splitted[i];
out.push(temp);
quoteStarted = false;
temp = "";
} else {
out.push(splitted[i])
}
}
return out;
}
It can be achieved in pure javascript like this way
let str = '"pen pineapple" "apple" "pen" "pen pen"'
let obj = {}
let pattern = /".*?"/g;
let index = ["a","b","c","d","e"]
let i=0
let key
while(current = pattern.exec(str))
{
key = index[i]
obj[key] = current[0].replace('"','')
i++
}
console.log(obj)
Can someone help me to do these example?
var a = ["17","18"];
var b = ["1","1","1"];
I need an output below:
var c = [17:111,18:111]
var a = ["17","18"];
var b = ["1","1","1"];
var i=0;
var ConcateC="";
for(i=0;i< b.length;i++)
{
ConcateC +=b[i];
}
var c=[];
for(i=0;i< a.length;i++)
{
c[i]=a[i] + ":" + ConcateC;
alert(c[i]);
}
You can join the values of b together, then use map to create a new array from the indices of a:
var a = ["17","18"];
var b = ["1","1","1"];
var bValue = b.join("");
var c = a.map(function(currentValue) {
return currentValue + ":" + bValue;
});
console.log(c); // ["17:111","18:111"]
How to split a string at a specific point defined by a number?
In example generate two variables, t1 and t2 from the string '123456' and have it split at character 3 so t1's value is '123' and t2's value is '456'...
var s0 = '123456';
console.log(s1);//123
console.log(s2);//456
I'd suggest:
var s0 = '123456',
t1 = s0.substring(0, s0.indexOf(3) + 1),
t2 = s0.substring(s0.indexOf(3) + 1);
References:
String.prototype.indexOf().
String.prototype.substring().
If you meant the 3rd character:
var ch = 3;
var s0 = "123456";
var s1 = s0.substr(0,ch); // will be '123'
var s2 = s0.substr(ch); // will be '456'
You can just do this.
var s0 = '123456';
var arr = s0.split('3');
var t1 = arr[0] + '3', t2 = arr[1];
Something like:
var foo = '123456'
,bar = [foo.slice(0,3), foo.slice(3)];
//=> bar now ["123", "456"]
Extend the String prototype:
String.prototype.splitAt = function(n) {
return n && n < this.length
? [this.slice(0,n), this.slice(n)]
: this;
}
// usages
'123456'.splitAt(3); //=> ['123', '456']
'123456'.splitAt(2); //=> ['12', '3456']
'123456'.splitAt(12); //=> '123456'
'123456'.splitAt(); //=> '123456'
Try
var s0 = "123456"
, s1 = s0.slice(0, 3); // first 3 characters in string , `123`
, s2 = s0.slice(- (s0.length - s1.length) ); // remainder of string , `456`(+)
console.log(s0, s1, s2)
var s = '123456';
var sos = 3;//number to split by
var t1 = '';
var t2 = '';
for (var i = 0; i < s.length; i++)
{
if (i<sos) {t1 += s[i];}
else {t2 += s[i];}
}
console.log('t1 = '+t1);
console.log('t2 = '+t2);
I have this function:
function myfunc(obj, properties, value) {
$.each(properties, function(i, key) {
var a = '-webkit-border-' + key + '-radius';
var b = '-moz-border-radius-' + key.replace(/\-/g, '');
var c = 'border-' + key + '-radius';
var z = value+'px';
obj.css({a : z, b: z, c: z});
});
}
Called like this:
myfunc($tab, ['top-left', 'top-right'], defaults.tabRounded);
Note that if I replace the obj.css line with:
obj.css({'border-top-right-radius': value+'px'});
It works as intended. Yet the values of a, b, c are completely correct.
What is going on?
The keys of an object literal in JavaScript are strings, not variables. If you do not quote them yourself, they are auto-quoted. So if you write
var a = {b: 1};
it's the same as if you had written
var a = {'b': 1};
You have to use [] to set keys dynamically.
var a = {};
a[b] = 1;
In this case modify your function to
function myfunc(obj, properties, value) {
$.each(properties, function(i, key) {
var a = '-webkit-border-' + key + '-radius';
var b = '-moz-border-radius-' + key.replace(/\-/g, '');
var c = 'border-' + key + '-radius';
var z = value+'px';
var css = {};
css[a] = css[b] = css[c] = z;
obj.css(css);
});
}