Why i can't give "1" as keyname in local Storage? - javascript

I want to give key name as "1" but its not working.
I want to pass a string like this in local storage with key "1" eg
1:["name":"kalidas"]
var array = [];
t = "kalidas";
t1 = "array";
if (localStorage.getItem("1") === null) {
a = [
{
name: t,
},
];
localStorage.setItem("1", JSON.stringify(a));
array = JSON.parse(localStorage.getItem("1"));
} else {
array = JSON.parse(localStorage.getItem("1"));
a = {
name: t,
};
array.push(a);
localStorage.setItem("1", JSON.stringify(array));
}
The output I'm always getting is Storage 
{1: "1", length: 1}
However, if I change key name it works perfectly.

localStorage.setItem('1', 'Some String here') works as expected.
Yes, the response of your code would be
[{…}]
0: {name: "kalidas"}
length: 1
If you look at your storage like console.log(localStorage) you will get
Storage {1: "1", length: 1}
1: "1"
length: 1
that's true
However, if you try to fetch stored data by key i.e. localStorage.getItem('1') you will get your valid response
"[{"name":"kalidas"}]"

You could write a simple wrapper that always roundtrips things to JSON:
function saveValue(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function loadValue(key, defaultValue=null) {
const value = localStorage.getItem(key);
if(value === null) return defaultValue;
return JSON.parse(value);
}
const a = {name: 'kalidas'};
saveLocalStorage('1', a);
const b = loadLocalStorage('1');

Related

Javascript Object manipulation to create an Object list with a variable id

I am not comfortable with certain subtleties, and here are 2 days that I go around in circles, to carry out "manipulations" of Objects in javascript (NodeJS), I therefore appeal to your knowledge!
I send elements from a json as a parameter in a .js script.
in this script, I would like to process the elements sent as a parameter (by a loop), to add them to a list, then to be able to add others "manually", to finally get a "list" of the set with different additional information.
my "test" script where I simulate the parameters received and "try" to get this "list":
let params = JSON.parse('{ "100": 3, "101": 1 }') // simulate parameters
let lstObj = {} // content all the list obj
// only for the test
function foo(type) {
return "type is " + type;
}
function addToList(id, type) {
let obj = {
id: id,
type: type,
test: foo(type)
}
console.log('from addToList() -> ', obj);
return obj;
}
// process the Obj from parameters
let index = 0;
for (let [key, value] of Object.entries(params)) {
console.log("from Param: ", `${key} -> ${value}`, " or ", key, "->", value);
obj = addToList(key, value); // seem work
//lstObj.key = obj; // use 'key' not the key value
//lstObj.[key] = obj; // error
//lstObj.`${key}` = obj; // error
//lstObj.["999"] = obj; // error
//index++; lstObj.index = obj; // bad :)
lstObj.a999 = obj; // Work ! but how can a make it ?
}
console.log('\nResult -> ', lstObj);
// Now want to manualy add other Obj in the List, like this ?
// lstObj.999 = addToList("999", 3)
I would like to get a result like this:
{
"100": {id: 100, type: 1, test: 'Type is 1', ....}
"102": {id: 102, type: 3, test: 'Type is 3', ....}
"110": {id: 110, type: 1, test: 'Type is 1', ....}
"305": {id: 305, type: 2, test: 'Type is 2', ....}
}
The purpose of being able to subsequently retrieve the object of an element by a call like: "lstobj.101"
Thank's a lot !
What you need is to assign the key to the object.
Change this line
lstObj.a999 = obj; // Work ! but how can a make it ?
to
lstObj[key] = obj;
What this does is assign whatever value is contained by variable key to be a key in variable lstObj, then assign the value of obj as it's value.
For example
let key = 'exampleKey';
let value = 'exampleValue';
let obj = {};
obj[key]=value; //now object is { 'exampleKey': 'exampleValue' }

How to convert url array query to object in Javascript

I have an URL with query params like this:
myLocalSite/?attributes%5B0%5D%5Bname%5D=customer_property_number&attributes%5B0%5D%5Bop%5D=equal&attributes%5B0%5D%5Bvalue%5D=12&attributes%5B1%5D%5Bname%5D=feedback_tags&attributes%5B1%5D%5Bop%5D=in&attributes%5B1%5D%5Bvalue%5D=test+1%2Cwww
after JSON parsing it convert into next structure
{
attributes[0][name]: "customer_property_number"
attributes[0][op]: "equal"
attributes[0][value]: "12"
attributes[1][name]: "feedback_tags"
attributes[1][op]: "in"
attributes[1][value]: "test 1,www"
}
In the end, I need an array that look like this:
attributes = [
{
name: 'customer_property_number',
op: 'equal',
value: '12',
},
{
name: 'feedback_tags',
op: 'in',
value: 'test 1, www',
},
]
Now does anyone know how I can then put these items into attributes array?
Thanks!
Here is the approach using URLSearchParams and going over each search param, parse and push to array of objects.
var sp = new URLSearchParams(
"myLocalSite/?attributes%5B0%5D%5Bname%5D=customer_property_number&attributes%5B0%5D%5Bop%5D=equal&attributes%5B0%5D%5Bvalue%5D=12&attributes%5B1%5D%5Bname%5D=feedback_tags&attributes%5B1%5D%5Bop%5D=in&attributes%5B1%5D%5Bvalue%5D=test+1%2Cwww"
);
var attributes = [];
for (entry of sp) {
const [attr, value] = entry;
const [index, key] = attr
.split("[")
.filter(x => x.includes("]"))
.map(x => x.slice(0, -1));
if (!attributes[Number(index)]) {
attributes[Number(index)] = {};
}
attributes[Number(index)][key] = value;
}
console.log(attributes);

JSON conversion for outer key value pair

I have one JSON in following structure:
data = {
"a" : "1",
"b" : {
"c" : 2
}
}
I want to convert it to following structure:
data = {
a = "1",
b = {
"c":2
}
}
I have tried to use map, but not getting correct way to do the conversion.
Try this:
const data = {
a: "1",
b: {
c: 2
}
};
const convertJson = data => {
const _data = [];
Object.keys(data).forEach(key => {
_data.push(`${key}=${JSON.stringify(data[key])}`);
});
return `{${_data.join(",")}}`;
};
console.log(convertJson(data));

How to put first objects into other object in java script and to make a single object

I have two input objects.
1.
var inputData1 = {
'st1': {
'name': 'k1',
'rollNo': 'abc'
},
'st2': {
'name': 'k2',
'rollNo': 'pqr'
}
};
2.
var inputData2 = {
'result': {
'data': 'sdg'
}
};
How to put first object into the other object. This is the expected output :
Output Object
var output = {
'result': {
'data': 'sdg',
'st1': {
'name': 'k1',
'rollNo': 'abc'
},
'st2': {
'name': 'k2',
'rollNo': 'pqr'
}
}
};
let say this is your first object.
var inputData1 = {
'st1':{'name':'k1', 'rollNo':'abc'},
'st2': {'name':'k2', 'rollNo':'pqr'}
};
and this is second object
var inputData2 = {
'result': {
"data": "sdg"
}
};
you can use simply like this
Object.assign(inputData2.result, inputData1);
console.log(inputData2);
What you want to do is the following :
// returns a new independant copy from the inputs
function combine(inputData1, inputData2) {
if (!inputData1 instanceof Object || !inputData2 instanceof Object) {
return {};
}
let output = Object.assign({}, inputData2);
Object.assign(output.result, inputData1);
return output;
}
var output = combine(inputData1, inputData2);
Well first off you can't have duplicate keys in an object. I suggest numbering them, and then you can just assign the contents of st1, st2 to the matchibng props in the output onject:
var inputData1 = {
'st1':{'name':'k1', 'rollNo':'abc'},
'st2': {'name':'k2', 'rollNo':'pqr'}
};
var inputData2 = {
'result': {
"data": "sdg"
}
}
So now you want to use Object.assign(obj, obj) to combine your objects:
var output = Object.assign(inputData1.result, inputData2);
This will combine your objects and give you what you want I hope. This method was added in ES6.
Let me know if this works, and remember to pick a winning answer :P

React: Calling filter on Object.keys

A React component is passed a state property, which is an object of objects:
{
things: {
1: {
name: 'fridge',
attributes: []
},
2: {
name: 'ashtray',
attributes: []
}
}
}
It is also passed (as a router parameter) a name. I want the component to find the matching object in the things object by comparing name values.
To do this I use the filter method:
Object.keys(this.props.things).filter((id) => {
if (this.props.things[id].name === this.props.match.params.name) console.log('found!');
return (this.props.things[id].name === this.props.match.params.name);
});
However this returns undefined. I know the condition works because of my test line (the console.log line), which logs found to the console. Why does the filter method return undefined?
Object.keys returns an array of keys (like maybe ["2"] in your case).
If you are interested in retrieving the matching object, then you really need Object.values. And if you are expecting one result, and not an array of them, then use find instead of filter:
Object.values(this.props.things).find((obj) => {
if (obj.name === this.props.match.params.name) console.log('found!');
return (obj.name === this.props.match.params.name);
});
Be sure to return that result if you use it within a function. Here is a snippet based on the fiddle you provided in comments:
var state = {
things: {
1: {
name: 'fridge',
attributes: []
},
2: {
name: 'ashtray',
attributes: []
}
}
};
var findThing = function(name) {
return Object.values(state.things).find((obj) => {
if (obj.name === name) console.log('found!');
return obj.name === name;
});
}
var result = findThing('fridge');
console.log(result);
You need to assign the result of filter to a object and you get the result as the [id]. You then need to get the object as this.props.things[id]
var data = {
things: {
1: {
name: 'fridge',
attributes: []
},
2: {
name: 'ashtray',
attributes: []
}
}
}
var name = 'fridge';
var newD = Object.keys(data.things).filter((id) => {
if (data.things[id].name === name) console.log('found!');
return (data.things[id].name === name);
});
console.log(data.things[newD]);

Categories