Search into a json file a value with only javascript and fs - javascript

i want to create a javascript function for search into a json file a object with the value.
getByValue(value) {
//the code
}
When i call the function, i need to search into a json file (the path is "./database/table.json") what i passed with value parameter, and return the object name.
An example:
JSON file:
{"name": "test"}
getByValue(value) {
//code for search into the file
}
//search on the json file a object value with "test"
console.log(getByValue("test"))
//expected output: "name"

You can do something like this :
const json = { "name": "test" , "name1" : "test1"}
const getByValue = value => {
for (let key of Object.keys(json)) if (json[key] === value) return key;
}
//search on the json file a object value with "test"
console.log(getByValue("test"))
//expected output: "name"

You need to first load that JSON in JS environment and parse it to read. In node.js you can do something like this
const jsonFromFile = require('filepath/file.json')
After reading the JSON, you just need to find the key where the value is given. There are multiple approaches to this. The basic solution is need to iterate over the object and find the value which matches.
One such approach:
const findKeyBasedOnValue = (obj, value) => Object.keys(obj).find((key) => obj[key] === value)
const data = {a: 'no-test', b: 'test'}
console.log(findKeyBasedOnValue(data, 'test')) // b

Related

How to convert a string to object and loop in react

I have a object which I am getting from database
Note: The below array is the output of console.log(ansoptions);
[{id:1, option:"Yes"},{id:2, option:"No"},{id:3, option:"Other"}]
This initially is in datatype string. I want to convert it into array of objects and loop to get id and option values.
I have tried below code
var ansoptions = JSON.parse(JSON.stringify(props.answerOptions));
console.log(ansoptions);
Array.from(ansoptions, item => {
console.log(item);
})
For the console.log(item) I am getting the output as weird as below
[
{
i
d
:
1
,
o
p
and so on.....
How do I get it? Please help !!
Parse the JSON (a string), then just loop over the array that's created.
const json = '[{"id":1, "option":"Yes"},{"id":2, "option":"No"},{"id":3, "option":"Other"}]';
const arr = JSON.parse(json);
for (let obj of arr) {
console.log(obj.id, obj.option);
}

Javascript: How to push key:pair values in Javascript Object which is already created

My question Explanation:
I have a variable of type = new FormData()
It has some key pair values for example.
const _CheckOutData = new FormData(); // Creating FormData object to send mulitpart data
_CheckOutData.append('Name', this._CheckOutForm.get('name').value);//Appending values to the
_CheckOutForm varibale from FormGroup
_CheckOutData.append('Street', this._CheckOutForm.get('street').value);//Appending values to the
_CheckOutForm varibale from FormGroup
_CheckOutData.append('City', this._CheckOutForm.get('city').value);/
I want to save these values in localStorages. when I directly save _ChechOutData to local storage its empty. Snippet of this function is
SaveFormDataToLocalStorage(_CheckOutData){
localStorage.setItem('_CheckOutData',JSON.stringify(_CheckOutData));
}
So getting empty local Storage. I tried a different apporach which actually work but as my Question is I want to push the values from the _CheckOutData (Type FormData) into new object. here is the snippet
_CheckOutData.forEach((key,value)=>{
let Value=key;
let Key=value;
let TemporaryCart={
[Key]:Value
}
this._CartCheckOutData.push(TemporaryCart);
})
So I am Successfully getting all and values and save them into TemporaryCart (type Object). But the Problem is if there are 5 values it is created 5 object in the Array.But I want to creat one Object with 5 values in it.
My Actual Result:
[{Name: "Fazi"}, {Street: "10570 S De Anza Blvd, Cupertino, CA 95014, United States"}]
But What I want
[
{
Name:"Fazi",
Street:"xyz 123",
.
.
.
.
And So One
}
]
Please Help me community: Regards Abdul Rehman
Hi you can try this one to change formdata in object
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
I would try to set the keys of the object this way:
some_list = []
some_object = {}
some_object['new_key_1']=123
some_object['new_key_2']='abc'
some_object
some_list.push(some_object)
will give you
> some_object
{ new_key_1: 123, new_key_2: 'abc' }
> some_list
[ { new_key_1: 123, new_key_2: 'abc' } ]
Because you want to copy one object into another you could also try alternatively:
> target_object = {...some_object, and_another_key:'123.123'}
{ new_key_1: 123, new_key_2: 'abc', and_another_key: '123.123' }
good luck!
A FormData object will look more like an array of arrays than an actual object. That's basically why a FormData object can have more entries with the same key.
So instead of trying to convert the FormData into an object into JSON, try to turn in into an array.
const formDataToJSON = formData => {
const entriesArray = [...formData];
return JSON.stringify(entriesArray);
}
This will first turn the FormData object into an array that looks like this (before the JSON step):
[
["Name", "Fazi"],
["Street", "xyz 123"],
]
This format will keep all the values in the FormData intact, as you could have multiple keys with the same name.
Reversing the process can be done as well.
const JSONtoFormData = json => {
const formData = new FormData();
const entriesArray = JSON.parse(json);
for (const [name, value] of entriesArray) {
formData.append(name, value);
}
return formData;
};

Dynamically create a nested JavaScript object with unknown keys

Let's say I have two arrays which are returned in a response from a REST call. For simplification I defined them hard-coded as keys and subKeys in the following example code.
From these arrays I'd like to create a nested object which, when outputted as a JSON string, looks like this:
Target JSON
{
"key1": {
"subKey1": "someValue"
},
"key2": {
"subKey2": "someValue"
},
"key3": {
"subKey3": "someValue"
}
}
Code sample
var keys = ["key1", "key2", "key3"]; // These come from a REST response
var subKeys = ["subKey1", "subKey2", "subKey3"]; // These come from a REST response
var targetObj = {}
for (const key in keys) {
targetObj[key] = {}
for (const subKey in subKeys) {
targetObj[key][subKey] = "someValue";
}
}
console.log(JSON.stringify(targetObj, null, 2));
While this gives me the correct behavior in my application I have the impression that there might be simpler approaches to achieve the same result, either in "vanilla" JavaScript or ES6? What bothers me here is that I define an empty object in each run of the for loop.
Your code does not produce the example output you said you want. It will put all 3 subkeys under each key, not one per key. Also you end up with numeric keys, not the key names.
var keys = ["key1", "key2", "key3"]; // These come from a REST response
var subKeys = ["subKey1", "subKey2", "subKey3"]; // These come from a REST response
var targetObj = {}
for (let i=0; i<keys.length; i++) {
const key = keys[i];
targetObj[key] = { [subKeys[i]]: "someValue" };
}
console.log(JSON.stringify(targetObj, null, 2));
First you were using "in" instead of "of" in the for-loop, and secondly you were not using the same index to find the subkey.
To avoid creating an empty object you can use this syntax:
{ [variable]: "value" }
This creates the object with the variable value as the key, and a string as the value. Putting the variable name in square brackets tells it to use the variable value rather than its name. Saying { variable: "value" } wouldn't work because the key would be "variable" not the value of variable.
Just use Array.prototype.reduce method:
const keys = ["key1", "key2", "key3"];
const subKeys = ["subKey1", "subKey2", "subKey3"];
const result = keys.reduce((acc, key, index) =>
({ ...acc, [key]: { [subKeys[index]]: 'someValue' } })
, {});
Note, this works only if keys and subKeys arrays are synced and their indexes are consistent with each other.

how to generate a URL from JSON object?

UPDATE
Updated the JSON model
I have 2 JSON objects look like:
{
"scheme":"https",
"server":"example.com"
}
and
{
"scheme":"https",
"server":"example.com",
"path":"items",
"item":"apple",
"itemDetails":[
{
"country":"US",
"year":"2019"
}
]
}
I want to make them into URL such as
https://example.com or https://example.com/items?item=apple&country=US&year=2019
How can I do?
You could create a function which creates the URL based on the object provided.
Destructure the parameter to get scheme, server, path. Assign a default value to path since it is optional. Get the remaining unknown properties to a rest variable using spread syntax (Properties like item, itemDetails etc will be inside the rest object)
You can create the base URL using the first 3 variables using a template literal
To get the query string, you can use URLSearchParams constructor. It has several overloads. You can pass a query string or an object or an array of entries as parameter to the constructor. If the object is flat, you simply do, new URLSearchParams(rest).toString() to create the query string. But, since you have nested arrays and objects, we need to create an array of entries first (Something like: [[key1, value1], [key2, value2],...and so on]. Then the string will be key key1=value1&key2=value2. The values will also be properly encoded to replace space and special characters etc)
You can create a recursive function to get the nested entries. Loop through the entries of the given object. If the current value is an Array, recursively call the method for each object in the array and push it to entries. If the value is an object, recursively call the function on the value. This function will return a 2-dimensional array of all the key-value pairs in the object.
Then simply pass the entries to URLSearchParams to create the query string. If the query string is not empty, append it to the base URL with a prefix of ?.
function createURL({ scheme, server, path = '', ...rest }) {
let url = `${scheme}://${server}/${path}`;
let param = new URLSearchParams(getEntries(rest)).toString();
if (param)
url += "?" + param;
return url
}
function getEntries(o = {}) {
const entries = [];
for (const [k, v] of Object.entries(o)) {
if (Array.isArray(v))
entries.push(...v.flatMap(getEntries))
else if (typeof v === 'object')
entries.push(...getEntries(v))
else entries.push([k, v])
}
return entries;
}
console.log(createURL({
scheme: "https",
server: "example.com"
}))
console.log(createURL({
scheme: "https",
server: "example.com",
path: "items",
item: "apple",
"itemDetails": [{
"country": "US",
"year": "2019"
}]
}))
Maybe is not the best way, but you can try
var myjson = {
scheme:https,
server:example.com
};
var obj = JSON.parse(myjson);
document.getElementById("#div1").innerHTML = obj.scheme + obj.server;

How to sort by Array index on Mongoose using a variable instead of string?

I'm trying to sort my data based on the index value of a variable.
I want to have totalClicks[0], but the totalClicks[0] syntax don't work. I've searched and tried using 'totalClicks.0', which works fine. But I need to check the req.params.bossId to sort the data based on the array[req.params.bossId].
This first, hardcoded, code works.
User.find({}).sort({ 'totalClicks.0' : '1'}).exec(
function (err, data) {
res.json(data);
});
This code, which dynamically selects which array field to sort, don't work and the whole .sort method gets ignored.
var bossId = req.params.bossId;
var totalClicksId = 'totalClicks.' + bossId;
console.log(totalClicksId); // totalClicks.0
console.log(typeof(totalClicksId)); // string
User.find({}).sort({ totalClicksId : '1'}).exec(
function (err, data) {
res.json(data);
});
If the ID variable is 0, them I want to sort the data by totalClicks[0].
If the ID variable is 1, them I want to sort the data by totalClicks[1].
I need to receive a variable bossId and, using that variable, sort my data based on the array[bossId]. How could I do that?
Appendix:
Model:
[
{
"username": "p",
"totalClicks": [
67,
25
]
},
{
"username": "kk",
"totalClicks": [
61,
38
]
}
]
You can't set an objects keys with a variable containing a string literally like that, and your sort function basically takes an object as it's argument.
.sort({key : value})
to create an object with dynamic keys, we have to do
var obj = {};
var key = 'something';
obj[key] = 'value'; // now obj === {'something' : 'value'}
So the solution is to create the object first, then pass it in
var totalClicksId = 'totalClicks.' + req.params.bossId;
var obj = {};
obj[totalClicksId] = '1';
User.find({}).sort(obj).exec(function (err, data) {
res.json(data);
});

Categories

Resources