How to convert a single string to object - javascript

I have multiple objects and trying to do a condition based on the object name. I am trying to check the name of the object based on the variable, which is a string. Is there any way to convert a single value string to object
const showHtml= {
one: {
code: "<DIV>",
pos: "1"
},
two: {
code: "<Body>",
pos: "2"
}
}
const showcss= {
one: {
code: "text-align",
pos: "1"
},
two: {
code: "float",
pos: "2"
}
}
I have a string variable (showHTML and showcss). I want to return the code based on the variable, so i am doing
let uVariable = localstorage.getItem("ftype")
console.log(uVariable.one.code)
I should get
<DIV>
but as i am passing the string, I can't get the object name, is there any way to convert the uVariable into object?
Thank you

You want JSON.parse here. Localstorage only stores strings. In your case, the code would look something like this:
let uVariable = JSON.parse(localstorage.getItem("ftype"))
console.log(uVariable.one.code)
String => object, use JSON.parse
Object => string, use JSON.stringify

please read this code, might help you
so initially we have variable showHtml which contains json data.
you should try this
JSON.parse(localStorage.getItem('showHtml')).one.code
and you can try jsfiddle:
https://jsfiddle.net/dupinderdhiman/f5wz7Lv1/2/
for more explanation read below:
var showHtml= {
one: {
code: "<DIV>",
pos: "1"
},
two: {
code: "<Body>",
pos: "2"
}
}
var showcss= {
one: {
code: "text-align",
pos: "1"
},
two: {
code: "float",
pos: "2"
}
}
localStorage.setItem('showcss', JSON.stringify(showcss));
localStorage.setItem('showHtml', JSON.stringify(showHtml));
alert('showHtml '+JSON.parse(localStorage.getItem('showHtml')).one.code);
alert('showCss '+JSON.parse(localStorage.getItem('showcss')).one.code)

Related

yup.js object validation, allow any key but values must be string or string array

I am using https://github.com/jquense/yup#yup
I want to have an object validation schema for:
subObjectField: {
[thisKeyCanBeAnyString]: string | string[] // allow string or array of strings
}
I cannot find an example or a starting point to achieve this, any ideas?
I've put together a function which makes this easy:
export const objectOf = (schema) => ({
name: 'objectOf',
exclusive: false,
message: "Object values don't match the given schema",
test: value => {
return value === null || Object.values(value).every(schema.isValidSync(value));
}
});
example:
yup.object().test(objectOf(yup.number())).nullable()
this successfully passes for null and for objects of numbers like { foo: 52, bar: -12 }

Filter Array Using Partial String Match in Javascript

I have an array of objects where the value I need to filter on is buried in a long string. Array looks like:
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
},
So if I wanted to grab all the partnerId objects where value includes parent_sku how would I do that?
console.log(data.value.includes('parent_sku') returns cannot read property 'includes' of null.
EDIT:
Didn't think this mattered, but judging by responses, seems it does. Here's the full response object:
Response body: {
"data": {
"configurationByCode": [
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
}
I'm passing that into a re-usable function for filtering arrays:
const parentSkuPartners = filterArray(res.body.data.configurationByCode, 'parent_sku');
Function:
function filterArray(array, filterList) {
const newList = [];
for (let i = 0; i < array.length; i += 1) {
console.log('LOG', array[i].data.value.includes('parent_sku');
}
}
The problem is somewhere else. The code you've tried should work to find if a value contains a string – I've added it the snippet below and you'll see it works.
The issue is how you are accessing data and data.value. The error message clearly states that it believes that data.value is null. We would need to see the code around it to be able to figure out what the problem is. Try just logging to console the value of data before you run the includes function.
const data = {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}", "partnerId": 1
};
console.log('includes?', data.value.includes('parent_sku'));
You can use data.value.includes('parent_sku') as you have suggested. The issue here is that your object is nested inside an unnamed object.
try:
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
The problem was some of the values for value were null. Adding an extra conditional fixed it:
if (array[i].data.value !== null) {
Use lodash includes, and lodash filter like
let configurationByCode = [{
data: {
value: {
cols:["parent_sku"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 1
}
}, {
data: {
value: {
cols:["nothing"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 2
}
}];
let wantedData = _.filter(configurationByCode, (config) => {
return _.includes(config.data.value.cols, 'parent_sku');
});
console.log( wantedData );
https://jsfiddle.net/76cndsp2/

Check if key/value pair within an array exists using Underscore JS _contains method

If I have the following object:
var record = {
title: "Hello",
children: [
{
title: "hello",
active: true
},
{
title: "bye",
active: false
}
};
I want to use underscore to determine if one of the children within the record has or does not have a title equal to a variable that will come from a form post, but also needs to be case insensitive... So for example:
var child = { title: "heLLo", active: true }
And underscore ( and this is wrong, and what I need help with ):
if ( _.contains(record.children, child.title) ) {
// it already exists...
} else {
// ok we can add this to the object
}
So basically I don't understand how to do this with underscore when dealing with array objects that have multiple key/value pairs. Also what is the best method for ignoring case? Should this be done in the underscore _.contains function? Regex? Use toLowerCase() beforehand to create the variables? If someone types in any variation of "Hello", "HELLO", "heLLO", etc. I don't want the insert to take place.
Thank you!
Use _.find and RegExp with "i" case-ignore flag
var valueFromPost = "bye";
var someOfChildrenHasValueFromPost = _.find(record.children,function(child){
return child.title.match(new RegExp(valueFromPost,"i"));
});
Update
Here is an example #JSFiddle
JS code:
record = {
children:[
{title:'bye'},
{title:'Bye'},
{title:'Hello'}
]
}
var testValue = function(value) {
return _.find(record.children,function(child){
return child.title.match(new RegExp(value,"i"));
});
}
console.debug(testValue('Bye')); //returns object with "Bye" title
console.debug(testValue('What'));//returns undefined
console.debug(testValue('bye')); //returns object with "bye" title

how to reach a property in nested objects easily?

I have a nested object. here it is:
var Obj = {
a: {
state: {
started: false,
players: [],
hand: 0,
totalHand: 0,
teams: {
starter: {
name: "",
handPoints: [],
totalPoint: calc(Obj.a.state.teams.starter.handPoints)
}
}
}
}
};
Like you see , i need to use handPoints value to set totalPoint. Do i have to call that like this:
calc(Obj.a.state.teams.starter.handPoints)
is there some way about using this keyword or something else?
What if i had a more nested object? It looks like weird to me.
Thank you.
Have you tried your solution? It causes a syntax error. Obj isn't defined while you're trying to define it, and even if it was you wouldn't get the latest value of obj, because you're trying to set it as the current value of the array at runtime.
see here:
syntax error example
You want to make that property a function so that a user can get the current total when they access the function.
Like this:
totalPoint: function(){
return calc(Obj.a.state.teams.starter.handPoints)
}
working example
If you want to shorten the reference you can alias some part of it. For instance
totalPoint: function(){
var myStarter = Obj.a.state.teams.starter;
return calc(myStarter.handPoints)
}
You could instead make the variable totalPoint into a function and use this.
var Obj = {
a: {
state: {
started: false,
players: [],
hand: 0,
totalHand: 0,
teams: {
starter: {
name: "",
handPoints: [ 5,6 ],
totalPoints: function() {
return calc(this.handPoints);
}
}
}
}
}
};
Here is the jsFiddle example.

prototype JSON to Object

The following is part of a JSON string returned from the server:
{
col1: {
caption: 'Workspace',
combodata: {
c_0: {
id: 0,
value: 'Filter...'
},
c_1: {
id: 1,
value: 'Tax'
},
c_2: {
id: 2,
value: 'HR'
}
}
}
}
After eval, I can access .caption, and .combodata is visible in Firebug as an object, with c_0 and c_1 visible as objects inside .combodata, with id and value in both c_0 and c_1.
How do I step through each object in .combodata? I tried .combodata.each(c), but that throws an exception. I won't know the names of the objects in .combodata during run time.
You can use a regular for loop for that:
for(var key in obj.col1.combodata) {
var combo_obj = obj.col1.combodata[key];
...
}
Can I suggest that you do not eval() the JSON that's returned? What you should be doing is:
var jsondata = { ... };
var obj = JSON.parse(jsondata);
The reason is because eval'ing a string can be dangerous. Imagine if your JSON data looked like this:
"{ some json data here }; alert(document.cookie)"
When you eval that, the users cookie is displayed to them. Now think what happens if instead of alert, that cookie is posted to an attackers URL. They now have access to that users account if such exists.
if
var result = {col1: { caption: 'Workspace',combodata: {c_0: {id: 0,value: 'Filter...'},c_1: {id: 1, value: 'Tax'},c_2: {id: 2, value: 'HR'}}}};
then
for ( i in result.col1.combodata ) {
var item = result.col1.combodata[i];
//Do stuff with item
}
I have found the following to work as well and will use this:
Object.values(col1.combodata).each(function(c2) {
id = c2.id;
});

Categories

Resources