I want to convert data stored in one variable from an array to an object, then assign that converted data to another variable.
For example, take:
options = ["226:39"];
and convert ["226:39"] to {"226":"39"}, then assign the converted data to the convertedOptions variable.
How would I do that?
While the other answers are correct for the sample value you mentioned in the question, using substring instead of split will handle the case where the value may need to contain a ":" character.
var options = ["226:39", "ratio:226:39"];
var convertedOptions = {};
for(var i = 0; i < options.length; i++){
var separatorIndex = options[i].indexOf(":");
if(separatorIndex > -1) {
var name = options[i].substring(0, separatorIndex);
var value = options[i].substring(separatorIndex + 1, options[i].length);
convertedOptions[name] = value;
}
}
console.log(convertedOptions);
You can split the string using the : separator, create your convertedOptions object, and then assign.
var options = ['226:39'];
var splitOptions = options[0].split(':');
var convertedOptions = {};
convertedOptions[splitOptions[0]] = splitOptions[1];
console.log(convertedOptions);
You can do it by spliting the element of options by ':':
var options = ["226:39"];
convertedOptions = {};
var el = options[0].split(':');
convertedOptions[el[0]] = el[1];
console.log(convertedOptions);
OR:
var options = ["226:39"];
convertedOptions = {};
var [prop, value] = options[0].split(':');
convertedOptions[prop] = value;
console.log(convertedOptions);
OR:
var options = ["226:39"];
var [prop, value] = options[0].split(':');
convertedOptions = { [prop]: value };
console.log(convertedOptions);
You could split the string and map an object for each element of options for a new property.
var options = ["226:39"],
convertedOptions = Object.assign(
...options.map(a => (([k, v]) => ({ [k]: v }))(a.split(':')))
);
console.log(convertedOptions);
Use String#replace to format the string as JSON, and then convert to an object using JSON#parse:
var options = ["226:39"];
var convertedOptions = JSON.parse(options[0].replace(/([^:]+):([^:]+)/, '{"$1":$2}'));
console.log(convertedOptions);
Related
I want to extract the variables names from a string like this: "foo=valor bar=second", and so on.
To return:
{
foo: "valor",
bar: "second",
...
}
You can use Regex Look Aheads to check for a variable name that is preceded by an = symbol
var str = "foo=valor bar=second";
var varRegex = /\w+(?=(\s)*(\=))/g;
var valueRegex = /(?<=(\=)[\s'"]*)\w+/g;
var varArr = str.match(varRegex);
var valueArr = str.match(valueRegex);
console.log(valueArr);
let obj = {};
for(let i in varArr) {
obj[varArr[i]] = valueArr[i];
}
console.log(obj);
var str = "foo=valor,bar=second";
var obj = {};
str.split(",").forEach(
function(item){
if(item){
var vars = item.split("=");
obj[vars[0]] = vars[1]
}
});
console.log(obj)
Different approach from the previous answer: You can split the string on spaces and then map the result array, splitting on the equal sign to create your object (left side is property, right side is value)
If you need it your specific format you can reduce it to convert the array into one big object with all the values
let a = "foo=valor bar=second"
console.log(a.split(' ').map((i,v) => { return JSON.parse(`{"${i.split('=')[0]}": "${i.split('=')[1]}"}`);}))
let b = a.split(' ').map((i,v) => { return JSON.parse(`{"${i.split('=')[0]}": "${i.split('=')[1]}"}`);})
console.log(b.reduce(function(acc, x) {
for (var key in x) acc[key] = x[key];
return acc;
}));
Not necessarily the quickest answer (in terms of speed of submission), but less regular expressions to maintain and less variables to store.
function toJSON(str) {
const regex = /(\w+)\=(\w+)\s*/g;
let result = {};
let match;
while (match = regex.exec(str)) {
result[match[1]] = match[2];
}
return result;
}
console.log(toJSON("foo=valor bar=second"));
str = "books:book1, books:book2, houses:house1, houses:house2, person:james";
I want to convert above string to separate arrays or arrays within an object, something like:
books = ["book1","book2"];
houses = ["house1","house2"];
person = ["james"];
How can I do this in JavaScript?
var string = "books:book1, books:book2, houses:house1, houses:house2, person:james";
var hash = {};
var splitByComma = string.split(',');
function addKeyByVal( key, val ){
if(!hash[key]) hash[key] = [];
hash[key].push(val);
}
for( var s in splitByComma ){
var splitByColon = splitByComma[s].split(":");
addKeyByVal(splitByColon[0], splitByColon[1]);
}
console.log(hash);
You probably want an object, with keys containing the arrays.
var str = "books:book1, books:book2, houses:house1, houses:house2, person:james";
var obj = str.split(',').reduce( (a,b) => { // split the string on comma
var parts = b.trim().split(':'); // split the parts on colon
if (! (parts[0] in a) ) a[parts[0]] = []; // if no key, create an array
a[parts[0]].push(parts[1]); // push the value to the array
return a; // return the object for next iteration
}, {})
console.log(obj)
You can split on ', ' and reduce to an object containing key: []:
const string = "books:book1, books:book2, houses:house1, houses:house2, person:james";
const output = string.split(', ').reduce((obj, cur) => {
let [category, value] = cur.split(':');
if (!Array.isArray(obj[category])) {
obj[category] = [value];
} else {
obj[category].push(value);
}
return obj;
}, {});
console.log(output);
Something like this:
var string = "books:book1, books:book2, houses:house1, houses:house2, person:james";
var books = [];
var houses = [];
var person = [];
string.split(", ").forEach(function(e) {
switch (e.split(":")[0]) {
case "books":
books.push(e.split(":")[1]);
break;
case "houses":
houses.push(e.split(":")[1]);
break;
case "person":
person.push(e.split(":")[1]);
break;
}
});
The code goes like this:
Make three new arrays for books, houses, and person.
Split the string into an array, separating by ,.
Go through each element in the new array and split it into another array, separating by :
If the string on the left is books, houses, or person then append the string on the right to the books, houses, or person arrays, respectively.
This will put create global variables for you leveraging the window, but for the love of god please don't -- just use an object. While this answer is what you asked for, the other answers are what you really want.
var str = "books:book1, books:book2, houses:house1, houses:house2, person:james";
var splitStr = str.split(',');
var i;
var key;
var val;
var temp;
for (i=0; i<splitStr.length; i++) {
temp = splitStr[i].split(':');
key = temp[0].replace(/ /g,'');
val = temp[1];
if (!window[key]) {
window[key] = [];
}
window[key].push(val);
}
console.log(books, houses, person);
First, you can use the split string method twice to break down the data, then to make them into (almost) global variables, you can set them as window properties, however this can be dangerous if the values passed interfere with the existing properties.
var pairs = str.split(", ");
for(var i = 0; i < pairs.length; i++) {
var key = pairs[i].split(":")[0];
var val = pairs[i].split(":")[1];
if(window.hasOwnProperty(key)) {
window[key].push(val);
}
else {
window[key] = [];
window[key].push(val);
}
}
This method is not recommended for cases where the source of the string is unknown, as it directly modifies window properties, some of which may cause unexpected behaviour if overwritten.
RegExp method.
var string = "books:book1, books:book2, houses:house1, houses:house2, person:james",
arr = string.split(', '), obj = {}, res = [];
arr.forEach(function(v){
var array = [],
elem1 = v.match(/\w+(?=:)/),
elem2 = v.match(/(?:)\w+/g)[1];
if (!obj[elem1]){
obj[elem1] = [];
obj[elem1].push(elem2);
} else {
obj[elem1].push(elem2);
}
});
console.log(obj);
I have following JSON string :
{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}
I want location_id as
3,2
Simple:
var data = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var result = data.map(function(val) {
return val.location_id;
}).join(',');
console.log(result)
I assume you wanted a string, hence the .join(','), if you want an array simply remove that part.
You could add brackets to the string, parse the string (JSON.parse) and map (Array#map) the property and the join (Array#join) the result.
var string = '{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}',
array = JSON.parse('[' + string + ']'),
result = array.map(function (a) { return a.location_id; }).join();
console.log(result);
obj=[{"name":"Marine Lines","location_id":3}, {"name":"Ghatkopar","location_id":2}]
var res = [];
for (var x in obj)
if (obj.hasOwnProperty(x))
res.push(obj[x].location_id);
console.log(res.join(","));
var json = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var locationIds = [];
for(var object in json){
locationIds.push(json[object].location_id);
}
console.log(locationIds.join(","));
You can also look into .reduce and create a string manually
var d = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var location_id_str = d.reduce(function(p, c) {
return p ? p + ',' + c.location_id : c.location_id
},'');
console.log(location_id_str)
try this
var obj = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var output = obj.map( function(item){
return item.location_id;
});
console.log( output.join(",") )
var arr = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var location_array = [];
for( var i = 0; i < arr.length; i++ )
{
location_array.push( arr[i].location_id );
}//for
var location_string = location_array.join(",");
console.log(location_string);
Note: You may need to use JSON.parse() if the arr is in string format initially.
You can use for..of loop
var arr = [{
"name": "Marine Lines",
"location_id": 3
}, {
"name": "Ghatkopar",
"location_id": 2
}];
var res = [];
for ({location_id} of arr) {res.push(location_id)};
console.log(res);
I having the Object with Date as Key and Value as Locations. I want Get the locations based on the largest Date. Here the locations are same. The Date Key is in "MM/DD/YYYY" Format.
var obj ={};
obj['9/10/2016'] = "India-Chennai";
obj['9/15/2016'] = "Australia-Melborne";
obj['9/20/2016'] = "India-Delhi";
obj['9/25/2016'] = "India-Chennai";
Form the above object the largest Date(Key) is "9/25/2016" and the value would be "India-Chennai" How to get the value based on the largest key?
Thanks in Advance
You can use Object.keys(), Array.prototype.map(), Math.max(), Date.prototype.getTime(), Array.prototype.indexOf()
var obj = {};
obj['9/10/2016'] = "India-Chennai";
obj['9/15/2016'] = "Australia-Melborne";
obj['9/20/2016'] = "India-Delhi";
obj['9/25/2016'] = "India-Chennai";
var keys = Object.keys(obj);
var map = keys.map(function(date) {return new Date(date).getTime()});
var key = Math.max.apply(Math, map);
var value = obj[keys[map.indexOf(key)]];
console.log(value);
You might do something like this;
var obj = {},
latest = [];
obj['9/20/2016'] = "India-Delhi";
obj['9/10/2016'] = "Japan-Osaka";
obj['9/25/2016'] = "India-Chennai";
obj['9/15/2016'] = "Australia-Melborne";
latest = obj[Object.keys(obj).sort((a,b) => new Date(b).getTime() - new Date(a).getTime())[0]];
console.log(latest);
You can use Object.keys() to get a list of keys as an array, then .sort() that array:
var obj ={};
obj['9/10/2016'] = "India-Chennai";
obj['9/9/2016'] = "Australia-Melborne";
obj['9/25/2016'] = "India-Chennai";
obj['9/20/2016'] = "India-Delhi";
var parseDate = d => (d = d.match(/(\d{1,2})\/(\d{1,2})\/(\d{4})/)) && new Date(d[3],d[1]-1,d[2]);
var latestKey = Object.keys(obj).sort((a, b) => parseDate(a) - parseDate(b)).pop();
var result = obj[latestKey];
console.log(latestKey, result);
I've used a regex to parse the dates, so that the code can easily be adapted to other date formats, e.g., if you needed d/m/yyyy instead of m/d/yyyy.
I'm looking to stringify an object.
I want in output like this
{"1":{"valeur":"dalebrun","usager":"experttasp","date":"2013-08-20 16:41:50"}, "2": {"valeur":"test","usager":"experttasp","date":"2013-08-20 16:41:50"}}
But I get this
{"valeur":"dalebrun","usager":"experttasp","date":"2013-08-20 16:41:50"}, {"valeur":"test","usager":"experttasp","date":"2013-08-20 16:41:50"}
What I do
var objVal = {}; //value....
var data = {}; //other value....
var object = $.extend({}, objVal, data); //concat the object
JSON.stringify(object);
When you concat the object, you get an array; you want a map with two elements, using the id "1" and "2"
var objVal = {}; //value....
var data = {}; //other value....
var object = {}
object["1"] = objVal;
object["2"] = date;
JSON.stringify(object);
I found the solution !
I do an for loop on the object. And I iterate on each element in the object. Thank you for your help. The answer of #Giovanni help me to found the solution.
Solution:
var data = {}; //values....
var objVal = {}; //other values....
var final = {};
var index = 1;
for(var key in data)
{
final[index] = data[key];
index = index + 1;
}
final[index] = objVal;
JSON.stringify(final);
And the output is :
{"1":{"valeur":"dfgdfg","usager":"experttasp","date":"2013-08-23 10:36:54"},"2":{"valeur":"uuuuuuuuuu","commentaire":"defg","usager":"experttasp","date":"2013-08-23 10:37:26"},"3":{"valeur":"uuuuuuuuuu","commentaire":"yesssss","usager":"experttasp","date":"2013-08-23 10:38:38"}}