JavaScript to JSON with Keys [duplicate] - javascript

This question already has answers here:
How to convert URL parameters to a JavaScript object? [duplicate]
(34 answers)
Closed 3 years ago.
I am trying to convert the parameters from my URL (Example 1) to a JSON Object that looks like Example 2. Unfortunately when I use JSON.stringify() it converts it to Example 3. Can anyone please point me in the right direction for splitting this? I am not sure how to get the keys out.
Example 1 - Input
food=apple,banana,peach&store=walmart&customer=John
Example 2 - Desired Output
{"food": ["apple", "banana", "peach"], "store":"walmart", "customer":"John"}
Example 3 - Current Ouput
{"food=apple,banana,peach", "store=walmart", "customer=John"}
Edits:
Forgot "" in food list
What I tried
data = "food=apple,banana,peach&store=walmart&customer=John";
data = JSON.stringify(data);

Using split, split the string appropriately and insert values in the object
var str = 'food=apple,banana,peach&store=walmart&customer=John';
var arr = str.split('&')
var obj = {};
for (let i = 0; i < arr.length; i++) {
var x = arr[i].split('=')
if (i == 0) {
obj[x[0]] = [];
x[1].split(',').forEach(function(y) {
obj[x[0]].push(y)
})
} else
obj[x[0]] = x[1]
}
console.log(obj)

Related

Find a pattern in an array [duplicate]

This question already has an answer here:
Split String using multiple Selectors
(1 answer)
Closed 4 years ago.
I have this array:
resultArray = ["08:30-10:45", "15:15-17:30"]
I would like to write a javascript that reads this array and return true of the timeslots comes between 00:00 - 08:00.I have written below javascript but this seems not working.
for (var i = 0; i < resultArray.length; i++) {
var bar = /^00:^01:^02:^03:^04:^05:^06:^07:^08/;
if (bar.test(resultArray[i])) {
return true
}
};
I would want to exclude value if it is 08:01 and so on and strictly want to check between 00:00-08:00. Can someone help me on this ?
You are probably looking for something like this:
resultArray = resultArray.filter(e => e.test(pattern))

How to get object value in javascript [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 5 years ago.
I have one array which have all the properties of values for object .
something like this.
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
console.log(ab[act[0]]);
how to access value of object using act values?
You have to split the string act[0] as your object does not contain any key named "name.first":
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
var key = act[0].split('.');
console.log(ab[key[0]][key[1]]);
try this simple
var ab = {first: 'a',
last: 'b',
age: '24'}
var ac = [];
ac.push(ab);
console.log(ac[0]);
Agree that it isn't natively supported, but you can use a little rectifier function to iterate down the passed path and get the value. This could probably be optimized, but works:
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
function getProperty(inputObj, path) {
var pathArr = path.split('.');
var currentObjLevelOrOutput;
var i;
if (pathArr.length > 1) {
currentObjLevelOrOutput = inputObj;
for (i=0; i < pathArr.length; i++) {
currentObjLevelOrOutput = currentObjLevelOrOutput[pathArr[i]];
}
} else {
currentObjLevelOrOutput = inputObj[path];
}
return currentObjLevelOrOutput;
}
console.log(getProperty(ab,act[0]));

Create an object from a string using javascript [duplicate]

This question already has answers here:
split string in two on given index and return both parts
(10 answers)
Closed 6 years ago.
I have a string that looks like this:
YA...Y..............
I need to create an object out of this. I was going to try to create an array from the string (but can't see how) if there was a way of doing a split on character index.
Then I was going to loop through that array and create an object.
I had a solution a bit like this:
// Creat an array
var array = [];
// Get our string length
var len = profileString.length - 1;
// Loop through our lengths
for (var i = 0; i < length; i++) {
// Get our current character
var char = profileString[i];
// Push our character into our array
array.push(char);
}
// Create our object
var obj = {};
// Loop through our array
array.forEach(function (item, index) {
// Add our item to our object
obj['item' + index] = item;
});
// Return our object
return obj;
I need to know if there is a better way of doing this.
You could use Object.create.
console.log(Object.create([...'YA...Y..............']));
ES5
console.log(Object.create('YA...Y..............'.split('')));

How to sort object by key through JSON file parsing in D3.js [duplicate]

This question already has answers here:
Sorting object property by values
(44 answers)
Closed 7 years ago.
I have a JSON file (myfile.json) that looks like this:
{"3":["c","d"], "3.5":["j","k"], "1.5":["a","b"], "2.5":["x","y"] }
What I want to do open the file and sort it using d3.js file opening.
d3.json('myfile.json',function(err,datafull){
for (var myval in datafull) {
console.log(myval);
}
});
Now if I do that, the console.log will print they key in unsorted manner.
How can I sort the file?
This is different question, because it involves file parsing.
To sort object keys you can use Object.keys() method which gives an array of the given objects keys then you can use the array sort() method.
d3.json('myfile.json',function(err,data){
keys = Object.keys(data),
i, len = keys.length;
keys.sort(function(a, b) {
return a - b;
});
for (i = 0; i < len; i++)
{
var a = keys[i];
console.log(a + ':' + data[a]);
}
}
See http://jsfiddle.net/sjmcpherso/mvrWb/234/

Iterate through dictionaries in javascript and access values? [duplicate]

This question already has answers here:
How do I iterate over a JSON structure? [duplicate]
(13 answers)
Closed 8 years ago.
I am not a javascript expert, so I am sure what I am trying to do is pretty straight forward, but, here it is:
I have an array that comes down from a database, it looks like this:
[{"name":"aName","lastName":"aLastname"},{"name":"bName","lastName":"bLastname"}]
I want to iterate through all dictionaries found in the array and access the aName, aLastname etc... so all possible values found in each dictionary, a dictionary at the time.
I tried using eval(), I tried to use JSON.parse, but JSON.parse I think was complaining because I think the object was already coming down as JSON.
How can I do that in javascript?
Thanks
So then I tried to do what was suggested by the "duplicate" answer comment... I did this:
for(var i=0; i<array.length; i++) {
var obj = array[i];
for(var key in obj) {
var value = obj[key];
console.log(key+" = "+value);
}
}
Problem is that the log is out of order. I get this:
name = aName
name = bName
lastName = aLastName
lastName = bLastName
I want to be sure I iterate through the properties and values in order one dictionary at the time.
What am missing here?
var test = [{"name":"aName","lastName":"aLastname"},{"name":"bName","lastName":"bLastname"}];
for (var i = 0; i < test.length; ++i) {
alert(test[i].name + ", " + test[i].lastName);
}
http://jsfiddle.net/1odgpfg4/1/
You may want to try this.
var arr = [{"name":"aName","lastName":"aLastname"},{"name":"bName","lastName":"bLastname"}];
arr.forEach(function(d){
console.log(d.name, d.lastName);
});

Categories