简体   繁体   中英

How to access part of string contained in an object in Javascript

I have an object that looks like this

{'{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}': '' }

I want to access part of what's contained in it

For example, if it was a normal object I would've thought I could do

objectName.variable

or

objectName.["variable"]

First of all, You should parse json data.

var obj = JSON.parse('{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}');
console.log(obj.variable);
console.log(obj.text);

etc ...

Firstly, parse the JSON - then because the data is a key, use Object.keys , then get the variable property:

 const obj = {'{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}': '' }; const { variable } = JSON.parse(Object.keys(obj)[0]); console.log(variable); 

var obj = {'{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}': '' };
// get keys from obj
var keys = Obejct.keys(obj);
// loop keys array
keys.forEach((item) => {
   // !!! parse String to JSON !!!
   var parsedObj = JSON.parse(item);

   console.log(parsedObj.variable);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM