Destructuring props dynamically React - javascript

Imaging we have a props, a really large object:
{
"firstname": "John",
"lastname": "Doe",
"age": 11,
"mode: "expert",
"website": "stackoverflow.com"
"protocol": "https",
"job": "dev",
"env": "main",
..... and a lot of key-values pairs coming
}
What usually we are calling to create "component variables":
let {firstname,
lastname,
age,
mode,
website,
protocol,
job,
env
...and a lot of "keys" as variable names} = props
// so we can call variable, {age} for example
I don't like to type all these variables in let {}, do we have something dynamic to declare "all keys" dynamically? I am not sure it's possible.
Of course I can use {props.firstname} in my code.
There is a way to create dynamically variables in let {} scope?
Any help is appreciated.

You can get all keys dynamically by Object.keys
const obj = {
"firstname": "John",
"lastname": "Doe",
"age": 11,
"mode": "expert",
}
const keys = Object.keys(obj)
console.log(keys)
//from these keys, you can get values based on your needs
//the first key value is `firstname`
//the first value is `John`
console.log(keys[0], obj[keys[0]])

Do you want to use (destructure) some props, and leave the rest in another object?
You can do that with i.e.
let testobject = {
"firstname": "John",
"lastname": "Doe",
"age": 11,
"mode": "expert"
}
const {firstname, lastname, ...verySmartFunc} = testobject ;
console.log(verySmartFunc);
//now your object is verySmartFunc,
//created with those keys you haven't destructured, and has next properties
{
age: 11,
mode: "expert"
}
If that's not what you're looking for and I misunderstood your question, I'd say you're already having props as an object with all those keys.
EDIT: Maybe this is what you're looking for, based on Nick Vu's answer.
const obj = {
"firstname": "John",
"lastname": "Doe",
"age": 11,
"mode": "expert",
}
const keys = Object.keys(obj)
let i = 0;
for (var key in keys) {
window[keys[i]] = obj[keys[i]];
i++
}
console.log(firstname); //result is "John"

Related

Update properties of an object of an array

I have an array of objects and I need to update a few properties of a specific object inside the array and then run the findAndUpdateById call on it. I am trying to do this but its not updating and gives me an error of undefined name property. I guess I am not following the right procedure to update an update an object of javascript and because of this i need help.
Here is my array
let arr = [
{
"_id": "1234",
"customer": {
"firstName": "John",
"lastName": "Doe",
"email": "johndoe#gmail.com",
"address": "123 Caroline Street"
}
}
]
Now I am recieving parameter like this that i need to update in my object
let ctx = {
"params": {
"changeObject": {
"firstName": "Ali",
"email": "ali#gmail.com"
}
}
}
Given: "I am getting the array of object by making .find call against id and there will be only one customer object in the received array"
// Given
let arr=[{"_id":"1234","customer":{"firstName":"John","lastName":"Doe","email":"johndoe#gmail.com","address":"123 Caroline Street"}}];
let ctx={"params":{"changeObject":{"lastName":"Ali"}}};
arr[0].customer = Object.assign(arr[0].customer, ctx.params.changeObject);
console.log(arr);
I think you were using different properties changePayload and changeObject.
You may want to use the spread operator and map for this as well.
let arr = [
{
"_id": "1234",
"customer": {
"firstName": "John",
"lastName": "Doe",
"email": "johndoe#gmail.com",
"address": "123 Caroline Street"
}
}
];
let ctx = {
"params": {
"changePayload": {
"firstName": "Ali",
"email": "ali#gmail.com"
}
}
}
arr = arr.map( data => ({
...data,
customer: {...data.customer, ...ctx.params.changePayload}
}) );
console.log( arr );
NOTE: This will change all objects in your array, but that is what you were asking for.

How to add objects from existing JSON to an empty object in Node JS

I am trying to take JSON data information from a separate file and insert that info into a newly created object. I know there are a lot of similar questions, but how do you do this with Node JS? I've tried just about all the options from the following link with no success
Add new element to an existing object
Ex:
"EXTERNAL-DATA" : [
{
"clients" {
{
"firstName" : "Thomas",
"lastName" : "Johnson",
"profession" : "Carpenter",
"age": 27,
"education": {
"Diploma": true
}
},
{
"firstName" : "Jane",
"lastName" : "Simpson",
"profession" : "Teacher",
"age": 32,
"education": {
"Masters Degree": true,
"College Degree": true,
"Diploma": true
}
}
}
}
]
If I only want to capture, say firstName, lastName, and education and place each client in a new, empty object collectedData as their own individual objects, how would I go about doing that?
Assuming the EXTERNAL DATA is held inside a variable called data
I've tried the spread operator collectedData = {... collectedData[i], ...data[i]}, but it doesn't add each as new objects
I've tried using new Object(); each time I loop through, but I'm not sure how the left-hand side is supposed to look when there are thousands of objects from the external JSON file.
I've tried Object.assign(), but with no luck
I know I'm overthinking it, but does anybody have an idea even for what direction to go in? I feel burned out.
Would eventually look like this:
collectedData = {
{
"firstName": "Thomas",
"lastName": "Johnson",
"education": {
"Diploma": true
}
},
{
"firstName": "Jane",
"lastName": "Simpson",
"education": {
"Masters Degree": true,
"College Degree": true,
"Diploma": true
}
}
}
You can use Array.map() to go through the clients array (which, looks like a typo in your code... I'm assuming it's an array) and get the object the way you want it.
const collectedData = clients.map((client) => {
return {
firstName: client.firstName,
lastName: client.lastName,
education: client.education
};
});
This basically loops through each client and creates a new object for each one with only the properties you want. Then, a whole new array is returned and assigned to collectedData.

Performance related issue for javascript object

I wanted to know if there is some performance issue related in the two below coding paradigms. Which one is the best and why?
var data = [{
"name": "ABC",
"code": 1,
"age": 97
},{
"name": "XYZ",
"code": 12,
"age": 12
},{
"name": "LMN",
"code": 121,
"age": 172
}
];
var response = [];
Method1
data.forEach(function(entry){
var obj = {
"NAME": entry["name"],
"AGE": entry["age"]
};
response.push(obj);
});
Method2
data.forEach(function(entry){
var obj = {};
obj["NAME"] = entry["name"];
obj["AGE"] = entry["age"];
response.push(obj);
});
For output object, I need say suppose, only 10 keys out of 100 keys
The object has many keys in it. Only limited are shown in the example. Which coding standard to choose and why? Please, can anybody explain?
No need to create the objects and then make a Array.prototype.push() for everly loop iteration...
You can directly use Array.prototype.map() instead of Array.prototype.forEach() and better access the object property values by the dot notation:
const data = [{
"name": "ABC",
"code": 1,
"age": 97
},{
"name": "XYZ",
"code": 12,
"age": 12
},{
"name": "LMN",
"code": 121,
"age": 172
}
];
const response = data.map(obj => ({
NAME: obj.name,
AGE: obj.age
}));
console.log(response)
Both approaches are fine and one should not be "faster" than the other, at least not enough to justify using the other one. Use the one you like.
But, if you're still looking for closure. The first one should be faster since it defines the entire object all at one go. There's no "look-ups" the engine have to do. It's all done at one go.
On a separate note, consider using the dot notation, it should be faster since the engine will not have to create strings. So, change
entry["name"]
to
entry.name
Also, if this is your actual code and the purpose is to modify the result to have just name and age and no code. You can do
data.forEach(user => delete user.code)

using variable name instead of it's value with JavaScript and use it to change an "Object" key identifier

My question is how to change or use the variable name instead of value;
I want to use this snippet:
jsonData.forEach((data)=>{
data.newName= data.api_name;
delete data.api_name;
})
to change the incoming JSON data's key identifier and get that "oldName" from a variable like this
var api_name = "fName";
So for example if this data comes from JSON:
[{
"fName": "John",
"lname": "Smith"
} {
"fName": "Jane",
"lname": "hardy"
}]
and want to have this:
[{
"person_name": "John",
"lname": "Smith"
} {
"person_name": "Jane",
"lname": "hardy"
}]
but if I do it like the snippet I will get error because the JSON doesn't have api_name as it's key identifier.
I hope that I explained enough.
appreciate any help
Use data[api_name] instead of data.api_name . Read more about property accessors.
let jsonData = [{
"fName": "John",
"lname": "Smith"
},{
"fName": "Jane",
"lname": "hardy"
}];
let api_name = "fName";
jsonData.forEach((data)=>{
data.newName= data[api_name];
delete data[api_name];
})
console.log(jsonData);
Try with data[newName]= data[api_name];
eg
newName= 'fName';
api_name='apiName'

JSON Object to be Stored into an Array

I am currently trying to store JSON stringified objects into an array so I will be able to add new elements as I go along:
function GetAllPatients(){
var patient = null;
var patients = [];
patient = { "FirstName": "Stephanie", "Gender": "Female", "Id": "P8401", "LastName": "BARRON", "Title": "Ms", "ConsultantId": "d10", "CurrentWardAdmissionName": "Non Admitted", "DOB": "/Date(1187650800000+0100)/", "HospitalAdmissionDate": "/Date(1294848066000+0000)/", "NHSNumber": "4646399561" };
patient = { "FirstName": "Joan", "Gender": "Female", "Id": "50434619", "LastName": "SMITH", "Title": "Mrs", "ConsultantId": "d1", "CurrentWardAdmissionName": "Non Admitted", "DOB": "/Date(513039600000+0100)/", "HospitalAdmissionDate": "/Date(1332242252817+0000)/", "NHSNumber": "9999999999" };
}
and also a switch case getPatientFromStore(pid) function which will retrieve a record by pid
How would I go about achieving this?
Is there any more information which I would require to help get me closer to a solution?
Basically, I'm in the middle of creating a web application which will allow offline local storage at a disconnected state, and also sync with a database on the server.
You can insert elements into an array by using push:
For example:
patients.push({
"FirstName": "Stephanie",
"Gender": "Female",
"Id": "P8401",
"LastName": "BARRON",
"Title": "Ms",
"ConsultantId": "d10",
"CurrentWardAdmissionName": "Non Admitted",
"DOB": "/Date(1187650800000+0100)/",
"HospitalAdmissionDate": "/Date(1294848066000+0000)/",
"NHSNumber": "4646399561"
});
As far as looking up by id, rather than an array, it would be better to use an associative array, like so:
var patients = {};
function addPatient(patient) {
patients[patient.id] = patient;
}
Then in your method to return a patient given the patient's id, you can do:
function getPatient(id) {
return patients[id];
}
This is useful if you're going to be looking up patients by their id all the time.
You could also use multiple indexes to access the same patient.
E.g. if you wanted to use NHSNumber as well as id you could do the following in the addPatients() function:
var patients = { };
var nhsNumberMap = { };
function addPatient(patient) {
patients[patient.id] = patient;
nhsNumberMap[patient.NHSNumber] = patient;
}
So you could also have another function:
getPatientByNHSNumber(nhsNumber) {
return nhsNumberMap[nhsNumber];
}

Categories

Resources