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);
Related
In my JS code, i have string as
s = "{\"selector\":{\"owner\":\"tom\"}}"; // originally this is a query response
I want to extract the value of 'owner' which is tom in another variable, s1.
What would be the easiest way to do it?
To convert your data to an object use obj = JSON.parse(s)
Then obj.selector.owner Or
obj["selector"]["owner"] which is the recommended way to get JavaScript object values...
You are not selecting the right properties when accessing your response data. Also you do not need to use toString in JSON.parse. Because your response is already a string data.
You want to convert string data by using JSON.parse
Demo:
//Response # 1
let findOwner = "{\"selector\":{\"owner\":\"tom\"}}"
//Parse Data
let parseData = JSON.parse(findOwner)
console.log(parseData.selector.owner) //Tom
//Response # 2
let findOwner2 = "{\"response\":{\"colour\":\"black\",\"make\":\"Tesla\",\"model\":\"S\",\"owner\":\"Adriana\"}}"
//Parse Data
let parseData2 = JSON.parse(findOwner2)
console.log(parseData2.response.owner) //Adriana
You can use a function for this:
function get(path, obj) {
return path.split('.').reduce((acc, current) => acc && acc[current], obj)
}
const obj = "{\"selector\":{\"owner\":\"tom\"}}"
const parsed = JSON.parse(obj)
get('selector.owner', parsed) // return 'tom'
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);
I am getting a set of arrays in string format which looks like
[49,16,135],[51,16,140],[50,18,150]
Now I need to save them in an array of arrays. I tried it like
let array = [];
let str = '[49,16,135],[51,16,140],[50,18,150]';
array = str.split('[]');
console.log(array);
but it is creating only one array including all string as an element while I need to have
array = [[49,16,135],[51,16,140],[50,18,150]]
Add array delimiters to each end of the string, then use JSON.parse:
const str = '[49,16,135],[51,16,140],[50,18,150]';
const json = '[' + str + ']';
const array = JSON.parse(json);
console.log(array);
You are splitting it incorrectly, in the example, it will only split of there is a [] in the string
You can create a valid JSON syntax and parse it instead like so,
let str = '[49,16,135],[51,16,140],[50,18,150]';
let array = JSON.parse(`[${str}]`);
console.log(array);
Another way you could achieve this is by using a Function constructor. This method allows you to "loosely" pass your array.
const strArr = "[49,16,135],[51,16,140],[50,18,150]",
arr = Function(`return [${strArr}]`)();
console.log(arr);
I'm writing a method which should concatenate two strings(that are result of json stringify) into one string(which should look like json object with it's structure).
First one :
{"text":"klk","makeId":"9"}
Second one:
{"firstname":"jjk","lastname":"jkjk","email":"jjkjk#sdasd.com"}
How do I concatenate these two into one json string i.e :
{"text":"klk","makeId":"9", "firstname":"jjk","lastname":"jkjk","email":"jjkjk#sdasd.com"}
I could strip {" and "} then split by comma and achieve this result. I'm wondering is there better more smart way to do this?
These strings are JSON! Parse them, merge them like objects and stringify them again.
var data1 = JSON.parse(json1);
var data2 = JSON.parse(json2);
var data = merge(data1, data2); // implement merge!
console.log(JSON.stringify(data));
JSON should be available in all recent browsers.
function merge(obj1, obj2) {
var hasOwn = {}.hasOwnProperty;
for (var key in obj2) {
if (hasOwn.call(obj2, key)) {
obj1[key] = obj2[key];
}
}
return obj1;
}
How do I change a JSON object into an array key/value pairs through code?
from:
{
'name':'JC',
'age':22
}
to:
['name':JC,'age':22] //actually, see UPDATE
UPDATE:
...I meant:
[{"name":"JC"},{"age":22}]
May be you only want understand how to iterate it:
var obj = { 'name':'JC', 'age':22 };
for (var key in obj)
{
alert(key + ' ' + obj[key]);
}
Update:
So you create an array as commented:
var obj = { 'name':'JC', 'age':22 };
var obj2 = [];
for (var key in obj)
{
var element = {};
element[key] = obj[key]; // Add name-key pair to object
obj2.push(element); // Store element in the new list
}
If you're trying to convert a JSON string into an object, you can use the built in JSON parser (although not in old browsers like IE7):
JSON.parse("{\"name\":\"JC\", \"age\":22}");
Note that you have to use double quotes for your JSON to be valid.
There is no associative array in JavaScript. Object literals are used instead. Your JSON object is such literal already.