convert string to object key more than 2depths - javascript

I want to convert string to object's key
I know this logic
const object = { name : 'test' }
const string = name
object[string] = name
I have something problems about this.
const string = common.device.type.pc.name
object[string] <- this is not working

You can do this by split string to each value
values = string.split(".");
object[values[0]][values[1]][values[2]][values[3]][values[4]]
Example:
object = {value1: {value2: "123"}};
string = "value1.value2";
values = string.split(".");
object[values[0]][values[1]] //return "123"

Related

Replacing a string with object property

I have a string
var str="{name:'qwer',age:24,gender:'male'}"
and I have an object with same property
var object = {name : zxcvb}
By matching the property (name) of the object, I want to overwrite the property value inside the string with the value from the object. The desired output is:
newString = "{name:'zxcvb',age:24,gender:'male'}"
Please let me know if you need any clarifications. Can we achieve this by regex?
You can iterate over the object, building a RegExp out of the key and substituting the value on a match:
let str = "{name:'qwer',age:24,gender:'male',aname:'xyz',namey:'pqr'}";
const obj = {
name: 'zxcvb'
};
for (let [key, value] of Object.entries(obj)) {
const regex = new RegExp(`\\b${key}\\s*:\\s*'[^']+'`);
str = str.replace(regex, `${key}:'${value}'`);
}
console.log(str);

How to turn a string onto a map?

I need to turn a string formatted like that:
string = "John:31,Miranda:28"
Onto this;
obj = { "John" => 31, "Miranda" => 28 }
I did this :
const class = new Map();
array = string.split(",");
And obviously I do not know what do with it because after the split I get something like this:
["John:31", "Miranda:28"]
And I don't know how to turn it onto an object (using the ":" as a arrow)... Maybe I don't need to use the array as an intermediary? Any thoughts? Thanks
You can use split to split by comma, and then map on the resulting strings to split again by colon, and feed the resulting array of arrays into the Map constructor.
For instance, if you want the map keyed by the names, which I suspect you do:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => entry.split(":")));
console.log(map.get("John")); // "31" (a string)
If you want the numbers to be numbers, not strings, you'll need to convert them:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => {
const parts = entry.split(":");
parts[1] = +parts[1];
return parts;
}));
console.log(map.get("John")); // 31 (a number)
My answer here goes into some detail on your options for converting from string to number.
If you want the map keyed by value instead (which I suspect you don't, but...), you just have to reverse the order of the inner array entries:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => {
const [name, num] = entry.split(":");
return [num, name];
}));
console.log(map.get("31")); // John
So split on the commas, loop over it and split on the colon, and build the object.
var myString = "John:31,Miranda:28"
var myObj = myString.split(',').reduce(function (obj, part) {
var pieces = part.split(':')
obj[pieces[0]] = pieces[1]
return obj
}, {})
You could try something like this:
const data = "John:31,Miranda:28"
const splitData = data.split(',')
const result = splitData.reduce((newObject, item) => {
const [name, age] = item.split(':')
return {
...newObject,
[name]: parseInt(age)
}
}, {})
console.log(result)
I'll just add this here:
Basically, split string by the comma, then the colon.
Combine result into a map
const test = "John:31,Miranda:28";
console.log(test);
const obj = test.split(/,/).map(item => item.split(/:/));
console.log(obj);
const _map = new Map(obj);
console.log(_map);
console.log(_map.get("John"))

splitting string into an object JavaScript

I have this String result:tie,player:paper,computer:paper
I guess you could split into arrays and make a object and parse it an object, however this does not seem to be a good approach.
How would I get this String as a object?
let string = "result:tie,player:paper,computer:paper"
For this particular string, I'd turn the string into proper JSON by surrounding the keys and values with "s, and then use JSON.parse:
const string = "result:tie,player:paper,computer:paper";
const json = '{' + string.replace(/(\w+):(\w+)/g, `"$1":"$2"`) + '}';
console.log(JSON.parse(json));
Though, ideally, whatever serves you that string should be giving you something in JSON format, rather than forcing you to resort to a hacky method like this to deal with a broken input.
Split on ,, iterate through, and split each string on : and make an object key/value property based on that. Use destructuring for simplicity:
let string = "result:tie,player:paper,computer:paper";
let obj = {};
let propsArr = string.split(",");
propsArr.forEach(s => {
var [key, value] = s.split(":");
obj[key] = value;
});
console.log(obj);
Split on the , to get key:value tokens, split those by : to get the key and value, and add them to the reduced object that collects the key value pairs.
var temp = "result:tie,player:paper,computer:paper";
var obj = temp.split(',').reduce((result, token)=>{
var [key, value] = token.split(':');
result[key] = value;
return result;
}, {});
console.log(obj);

How to concatenate string and numbers to make a JSON object?

I want to make a JSON object like this:
let lob = { courses_dept: 'sci', courses_avg: 77.09 };
by concatenate variables together:
var dept = "sci";
var avg = 77.09;
let a = '{"courses_dept": dept, "courses_averge": avg }';
but I got SyntaxError if I do this:
let b = JSON.parse(a);
What is the proper way to do this?
Note JSON stands for JavaScript Object Notation. JSON is always a string. It is a string representation of your encoded data. There is no such thing as "a JSON Object".
Don't attempt to write JSON by joining strings and other values together. Instead build an object and pass it to JSON.stringify -
const dept = "sci"
const avg = 77.09
// make an object
const myobject = { courses_dept: dept, courses_average: avg }
// use JSON.stringify to encode myobject to JSON
const myjson = JSON.stringify(myobject)
console.log("encoded", myjson)
// test JSON.parse to decode the JSON and get the object back
console.log("decoded", JSON.parse(myjson))
encoded {"courses_dept":"sci","courses_average":77.09}
decoded {
"courses_dept": "sci",
"courses_average": 77.09
}
If you want to use strings:
var dept = "sci";
var avg = 77.09;
let a = `{"courses_dept": "${dept}", "courses_averge": ${avg} }`;
This assumes that dept is a string. If you don't know this in advance, wrap each variable with JSON.stringify:
let b = `{"courses_dept": ${JSON.stringify(dept)}
,"courses_averge": ${JSON.stringify(avg)}}`;
Notice that the string uses backticks ` instead of regular quotes. This allows you to do string interpolation. You can use + if you want to do straight up concatenation.
You can also just do a regular object:
let c = {"courses_dept": dept, "courses_averge": avg}
JSON.stringify(c)
Why not just plain json object then?
var dept = "sci";
var avg = 77.09;
let a = {
"courses_dept": dept,
"courses_averge": avg
};
console.log('a', a);
This way works and seems to be simpler.
let b = {};
b["courses_dept"] = dept;
b["courses_averge"] = avg;
You can make a JSON with single quotes and concatenate variables. After that you can parse the string.
var id_of_the_product = $('#is-a-gift').data( 'gift_product_id' ) ;
var items_in_cart = (cart_item_count) - (gift_wraps_in_cart);
$.ajax({
type: 'POST',
url: '/cart/update.js',
data: JSON.parse('{ "updates": { "'+ id_of_the_product +'" : "'+items_in_cart+'" }, "attributes": { "gift-wrapping": "'+gift_wrapping_type+'" } }'),
dataType: 'json',
success: function() { }
});

Unable to get the value from a JavaScript object

I have created a JSON object and put it under session object.
How can I retrieve the value from the JSON?
This is my program
var datainsession = {"firstName":"John", "lastName":"Doe"};
var keyname = 'test';
window.sessionStorage.setItem(keyname + '', datainsession);
var val_sess = window.sessionStorage.getItem(keyname);
var firstname = val_sess.firstName;
alert(firstname);
http://jsfiddle.net/5bea0mr2/3/
Could you please tell me how I can retrieve the first name?
Session storage can only hold strings, not objects. Your session here ends up holding your object converted to a string ("[Object object]"), and not the object itself.
To get around this we can firstly convert the object to a JSON string using JSON.stringify():
window.sessionStorage.setItem(keyname + '', JSON.stringify(datainsession));
-> '{"firstName":"John","lastName":"Doe"}'
Then when pulling it convert it back to an object by using JSON.parse():
var val_sess = JSON.parse(window.sessionStorage.getItem(keyname));
-> {"firstName":"John","lastName":"Doe"}
window.sessionStorage.setItem can only store serialised objects.
So you have to serialise it first via JSON.stringify:
window.sessionStorage.setItem(keyname, JSON.stringify(datainsession))
Then to retrieve it via JSON.parse:
var val_sess = window.sessionStorage.getItem(keyname);
var obj = JSON.parse(val_sess);
// obj.firstName is what you need.
JSON is represented by a string, not an object. It's simply a JavaScript object with string keys. You'll need to use JSON.stringify() and JSON.parse() to convert the JavaScript object.
Try the following:
var datainsession = {
firstName: "John",
lastName: "Doe"
};
var keyname = 'test';
window.sessionStorage.setItem(keyname, JSON.stringify(datainsession));
var val_sess = JSON.parse(window.sessionStorage.getItem(keyname));
var firstname = val_sess.firstName;
alert(firstname);
You need to convert it to a string on setting, and parse it when you get it out. This method only stores a string, but JSON methods can get around that. Eg.
var datainsession = {"firstName":"John", "lastName":"Doe"};
var keyname = 'test';
window.sessionStorage.setItem(keyname + '', JSON.stringify(datainsession));
var val_sess = window.sessionStorage.getItem('test');
var obj = JSON.parse(val_sess).firstName;
alert(obj);

Categories