Parsing Json in Node.js which holds numbers as its key param - javascript

My JSON holds numbers in its key param for an example:
"abc_12345_xyz":"value".
I am fetching this 12345 from my property file and framing the key param dynamically, while parsing it. For an example
var num=fetching from prop file(12345).
var jsonValue=jsonObj.value[0].abc_+num+_xyz
I am not getting the value while performing the above step, is there anyway to frame the key parameter dynamically.

Try using
jsonObj.value[0]["abc_"+num+"_xyz"]

If you will have a list in your properties file and want to get the value based on the entry, like using a regex to get any key that have the property content, you can loop through the keys and check if it have the word on the key. See below this example:
var obj = {
"abc_12345_xyz": "test_value_1",
"abc_qwert_xyz": "test_value_2"
};
var prop_file = [12345, 'qwert'];
for (var key in obj) {
if (key.indexOf(prop_file[1]) > -1) {
console.log(key, obj[key]);
}
}
Or if the key will always having the prefix and suffix static, you can simply:
obj["abc_"+ prop_value +"_xyz"];

Related

How to add to URL?

I am creating a filtering functionality and I would like to add the selected filters to the url for navigation purposes. Here is an array of objects:
let arr = [
{available:true},
{variantOption:{name:"size",value:"2XL"}},
{productType:"Apparel"}
]
I need it in the following format which I think are according to the W3c guidelines:
www.whatever.com/collection?available=true&productType=apparel&somethingElse=something etc
I am not able to figure out how to add something like variantOption key and values to the url in format like so. So that when I retrieve the values from the URL, they end up in the same format like the original array of objects was, which I want to use for the api call.
I would be using window.history.pushState for this use case here.
You will need to loop through the array.
for (let item of arr) {
then you will need to get each key of the object (item).
for (let key in item)
because one of them is another object you will need to check if the value is object
if (typeof item[key] === "object")
if true,
you need to loop one more time to get the extra key value pairs and pass them to the url as params..
for (let innerKey in item[key]) {
newLink.searchParams.set(innerKey, item[key][innerKey]);
else,
just take the key and value and pass them to the url as params.
newLink.searchParams.set(key, item[key]);
the loop at the end should look like this:
const newLink = new URL(window.location.href); // here you can put any base url
for (let item of arr) {
for (let key in item) {
if (typeof item[key] === "object") {
for (let innerKey in item[key]) {
newLink.searchParams.set(innerKey, item[key][innerKey]);
}
} else {
newLink.searchParams.set(key, item[key]);
}
}
}
and then to use the newLink.href as the url. you mentioned that you want to use window.history.pushState . so you can call the function and pass the url as argument.
example here: codesandbox example

How to compare dynamic string with static string in object with regex javascript

Let say I have one object with key as string which consists dynamic values-
let obj = {
"/prodp/v1/engagemnt/{engID}/doc/{docID}":"roles_1",
"/prodp/v1/engagemnt/{engID}/review/{reviewID}": "roles_2"
}
I want to compare and find value for below string from above object.
/prodp/v1/engagemnt/1234/doc/doc_1234
So as per requirement above string should return roles_1 value from object.
Can anyone suggest the solution for this issue?
you can use Object.keys(obj) to get all keys of an object as an array of string.
const obj = {
"/prodp/v1/engagemnt/{engID}/doc/{docID}":"roles_1",
"/prodp/v1/engagemnt/{engID}/review/{reviewID}": "roles_2"
}
let roles;
Object.keys(obj).forEach((key) => {
// key will be equal to "/prodp/v1/engagemnt/{engID}/doc/{docID}":"roles_1" then it will be equal to the next key of the object
roles = // do your regex here for whatever you want to check
});

Javascript reserved word and object

I'm making a dictionary of words, so there are 1,000,000+ words.
The problem comes when I need to store the word constructor. I know this is a reserved word in javascript, but I need to add it to the dictionary.
var dictionary = {}
console.log(dictionary ['word_1'])
//undefined, this is good
console.log(dictionary ['word_2'])
//undefined, this is good
console.log(dictionary ['constructor'])
//[Function: Object]
// this cause initialization code to break
How can I fix this? I could muck with the it like key=key+"_" but that seems bad. Is there anything else I can do?
Instead of using a JS object, you could use the built-in Map type which uses strings/symbols as keys and does not conflict with any existing properties.
Replace
var dictionary = {} with var dictionary = new Map()
Override the constructor key as undefined
According to the MDN Object.prototype page, the only thing that isn't hidden by the __fieldname__ schema is the "constructor field". Thus, you could just initialize your objects via { 'constructor': undefined }.
However, you would have to make sure that in your for .. in statements would filter out all keys with undefined as their value, as it would pick up constructor as a "valid" key (even though it wouldn't before you specifically set it to undefined). I.E.
for(var key in obj) if(obj[key] !== undefined) { /* do things */ }
Check for types when getting/setting
Otherwise, you could just check the type when you 'fetch' or 'store' it. I.E.
function get(obj, key) {
if(typeof obj[key] !== 'function') // optionally, `&& typeof obj[key] !== 'object')`
return obj[key];
else
return undefined;
}
I think you should store all words and translation of them in an array. When you need to translate a word, you can use find method of Array.
For example:
var dict = [
{ word: "abc", translated: "xyz" },
...
];
Then:
var searching_word = "abc";
var translation = dict.find(function (item) {
return item.word == searching_word;
});
console.log(translation.translated);
// --> xyz
To achieve expected result , use below option of using index to get value of any key value
var dictionary = {};
var dictionary1 = {
constructor: "test"
};
//simple function to get key value using index
function getVal(obj, val) {
var keys = Object.keys(obj);
var index = keys.indexOf(val);//get index of key, in our case -contructor
return obj[keys[index]]; // return value using indec of that key
}
console.log(getVal(dictionary, "constructor"));//undefined as expected
console.log(getVal(dictionary1, "constructor"));//test
console.log(dictionary["word_1"]);
//undefined, this is good
console.log(dictionary["word_2"]);
//undefined, this is good
codepen - https://codepen.io/nagasai/pen/LOEGxM
For testing , I gave one object with key-constructor and other object without constructor.
Basically I am getting the index of key first and getting value using index

how to insert new object in node js array if key not exist

I want to create data structure like that.
Var ans =[{"b":[1,2]},{"g":[100,2]}]
I want to create a new object within list if key not exists in list ans.
Else if key exists in one object of ans list then I want to add new values into the object of ans list
For Example:
Example 1) new data c:{2000}
then
Var ans =[{"b":[1,2]},{"g":[100,2]},{c:[2000]}]
Example 2) new data g:{50}
then
Var ans =[{"b":[1,2]},{"g":[100,2,500]},{c:[2000]}]
I am a beginner in node js, understand array, object concept, but not getting exact logic!
Thanks!
You can try following:
Logic
Filter array based on key
Check if object with mentioned key exists or not.
If yes, push value to this array.
If not, create a dummy object and push this object to original array.
Correction, when you do .push({key: value}), key will be considered as string.
Alternates
If you are using ES6, .push({ [key] : value })
Create a dummy object var o = {}. Set key and value to it o[key] = value and push this object.
Optimisations
Instead of setting value like obj[key] = value, since we will be operating on arrays, try obj[key] = [].concat(value). This will enable you to pass value as number or array of values.
Instead of checking the existence of value in .filter, try Array.isArray to check if value exists and is of type array.
Custom function
function checkAndPush(array, key, value) {
var filteredList = array.filter(function(o) {
return Array.isArray(o[key]);
});
filteredList.length > 0 ? filteredList[0][key].push(value) : array.push({
[key]: [].concat(value)
});
return array;
}
var ans =[{"b":[1,2]},{"g":[100,2]}]
console.log(checkAndPush(ans, "c", [2,3]))
console.log(checkAndPush(ans, "c", 4));
Prototype function
Array.prototype.checkAndPush = function(key, value) {
var filteredList = this.filter(function(o) {
return Array.isArray(o[key]);
});
var dummy = {}
dummy[key] = [].concat(value)
filteredList.length > 0 ? filteredList[0][key].push(value) : this.push(dummy);
// or ES6: this.push({ [key]: [].concat(value) })
return this;
}
var ans =[{"b":[1,2]},{"g":[100,2]}]
console.log(ans.checkAndPush("c", [2,3]))
console.log(ans.checkAndPush("c", 4));
If you are dealing with objects as your values
ans[key] = ans[key] || []
ans[key].push(value)
Note, this works because your values will be an array. If they could be primatives then you would use hasOwnProperty to check.
if (ans.hasOwnProperty(key)) {
// Add this to your key somehow
} else {
// initialize the key with your value
}
Node.js is nothing but a library built on javascript. You can do anything using javascript type of progmming. However push and pop method should be able to help you to deal with nodejs array.
ans[key].push(value)

add a value to localstorage, instead of replacing it

i want the value from newUsername to be added to the localStorage setUsernamesArray, whereas in my code, it replaces the entire value.
Code
$('#signUpButton').click(function() {
var newUsername = $('#usernameSignInBox').val();
signedUpUsernames.push(newUsername);
localStorage.setItem('setUsernamesArray', signedUpUsernames);
});
If you want to add to the array, you must realise that the value in localStorage isn't an array, it is a string. If you want that string to represent an array, and you want to update that array, you must do the following things:
read the string, localStorage.getItem('setUsernamesArray'),
then convert it to an array with JSON.parse,
then push to the array,
and then store it again with localStorage.setItem('setUsernamesArray', JSON.stringify(array))
localStorage always store values as a string, so stringify your array and store,
localStorage.setItem('setUsernamesArray', JSON.stringify(signedUpUsernames));
And before reading it just parse it,
var arrayFrmStorage = JSON.parse(localStorage.getItem("setUsernamesArray"))
localStorage.setItem will replace value of the key in localStorage.
Consider localStorage as a variable. when you do
var a = "Hello";
a = " World"
value of a is replaced. To avoid it, we use +=
var a = "Hello";
a += " World"
Similarly, you will have to create another object with updated value and write this to localStorage.
Following is an example.
function setValueToLS(key, prop, value){
var _local = {};
if(localStorage.getItem(key))
_local = JSON.parse(localStorage.getItem(key));
_local[prop] = value;
localStorage.setItem(key, JSON.stringify(_local));
}

Categories

Resources