JSON Stringfy only a few properties - javascript

I have this object:
{
name: "",
email: "",
phone: "",
protocol: "",
area: "",
subject: "",
message: "",
validation: this.validator.valid()
}
I wanna convert it to JSON, but I do not want the validation property on it.
I've already tried the following:
const test = JSON.stringify(this.state);
delete test.validation;
Any other approach?

JSON.stringify takes a replacer callback you can use. The replacer function takes a key k and the value v being stringified as parameters. Returning undefined will have the effect of not including the key in the final result:
state = {
name: "",
email: "",
phone: "",
protocol: "",
area: "",
subject: "",
message: "",
validation: "some val"
}
const test = JSON.stringify(state, (k, v) => k != 'validation' ? v : undefined);
console.log(test)
Note: used like this it will remove the validation key from any child objects as well, which may or may not be what you want.

It will work.
const { validation, ...rest } = this.state;
JSON.stringify(rest);

UPDATE - I found a different solution
It's very simple, in fact. I've discovered the solution here.
The following lines solved my problem:
const formSubmit = JSON.stringify(this.state, ['name', 'email', 'phone', 'protocol','area','subject', 'message']);

If you put an undefined, JSON.stringify will skip it:
const yourState = {
name: "",
email: "",
phone: "",
protocol: "",
area: "",
subject: "",
message: "",
validation: true,
}
const copy = {
...yourState,
validation: undefined,
};
console.log(JSON.stringify(copy));
Also, you can not perform a delete from JSON.stringify because it is a string an not an object literal.

Related

Filtering an object by multiple arguments(inputs)

I have a lot of inputs, after which my object is supposed to filter, I can hardcode it, but there is probably a smarter way to do it
Filter state :
const [filters, setFilters] = useState<FiltersType>({
login: "",
name: "",
surrname: "",
});
Example data:
const data: UserRow[] = [
{
key: "1",
login: "John#gmail.com",
name: "John",
surrname: "Smith",
role: ["user"],
},
{
key: "2",
login: "Andrew#gmail.com",
name: "Andrew",
surrname: "Johnson",
role: ["user"],
},
];
data.filter((e) => {
if (
(!filters.name || e.name.includes(filters.name)) &&
(!filters.surrname || e.surrname.includes(filters.surrname)) &&
(!e.login ||
e.login.toLowerCase().includes(filters.login.toLowerCase()))
) {
return true;
}
return false;
})
For example, it can be done like this, but as you can see it looks bad and scales poorly when adding new fields, I tried to simplify it using "Object.entries()", but ultimately failed :(. What is the best pattern for such a problem?
You should use some() (logical OR for all the conditions) or every() (logical AND for all the conditions) in combination with filter().
const data = [
{
key: "1",
login: "John#gmail.com",
name: "John",
surrname: "Smith",
role: ["user"],
},
{
key: "2",
login: "Andrew#gmail.com",
name: "Andrew",
surrname: "Johnson",
role: ["user"],
},
];
const filter = {
login: "",
name: "",
surrname: "",
};
const filters = Object.entries(filter);
const filtered = data.filter((user) =>
filters.some(
([key, value]) =>
user[key] && user[key].toString().toLowerCase().includes(value)
)
);
console.log(filtered);
Use some() if you want to include the result if any of the filter conditions is met and use every() if you want to only include a result if all filter conditions are met.
The above will work for simple filters. You can however extend the solution using typeof() or Array.isArray() function etc. to process different types like arrays, nested objects etc. accordingly.

TypeError: can't define array index property past the end of an array with non-writable length

i am updating state in form by dynamically adding form fields but this error is coming up
what i have tried
what should happen is that more fields should be added to each subfields on click if i want
const addExperience = () => {
let temp = Object.assign({}, form);
temp.experience.push({
company: "",
position: "",
startDate: "",
endDate: "",
description: "",
});
setForm(temp);
}
this is the form
const [form, setForm] = useState({
name: "adarsh raj",
email: "adarsh#gmail.com",
phone: "83404dvsdsd",
address: "patel chowk",
city: "deoghar",
education: [
{
school: "dav ",
major: "intermediate",
GPA: "8.12",
},
],
experience: [
{
company: "venturepact llc",
position: "associate software developer",
startDate: "dd-mm-yyyy",
endDate: "dd-mm-yyyy",
description: "description",
},
],
projects: [
{
projectName: "project name",
projectDescription: "project description",
},
],
skills: [
{
skillName: "your skill name",
},
],
});
Object.assign(target, source) just Shallow copy.
useState return value is Immutable;
Refer to the following demo
var x = new Array(10).fill(0);
Object.freeze(x);
x.push(11) // same error
You can solve this problem by deep copying or reassigning the experience of the first layer.
Only the first layer can be assigned because a shallow copy is used. It cannot be resolved if the problem attribute appears at the second level. Therefore, this method is not recommended and deep copy is recommended.
let temp = JSON.parse(JSON.stringify(form));
let temp = lodash.cloneDeep(form);// need install lodash
code like this should work. But to test, you can try this syntax:
const addExperience = () => {
let temp = Object.assign({}, form);
temp.experience = [
...temp.experience,
{
company: "",
position: "",
startDate: "",
endDate: "",
description: ""
}
];
setForm(temp);
};
I solved now a similar problem creating a new array with spread operator like this
const newMutableArray = [...immutableArray, newItem]
it works fine for me.

How do I push to an array that is nested in an object?

I have been working on this for hours and can't figure it out. I have a checklist object sorted by category, and each category is an array of task objects. I am trying to allow the user to add a task to a given category array, but cannot figure it out. Each time I try to log the array, it just prints out the observer and says that '.push' is not a function.
I think the issue is dealing with using a variable to get the array because when I hard code in 'masterChecklist["General Cleaning"]', it will work. Please help!
** The example below is simplified
var masterChecklist = {
"General Cleaning":
[
{cleaned: false, notes: "", name: 'Empty and sanitize trash bins'},
{cleaned: false, notes: "", name: 'Clean mirrors and windows'},
],
"Home Exterior":
[
{cleaned: false, notes: "", name: 'Wipe and clean all furniture'},
{cleaned: false, notes: "", name: 'Empty the trash bins'},
],
}
SaveTaskDetails("Dust", "Make sure to get the shelves", "General Cleaning")
function SaveTaskDetails(name, notes, category) {
var newTask = {
name: name,
notes: notes,
cleaned: false
}
var category = masterChecklist[category].push(newTask)
}
console.log(masterChecklist);
You can do:
const masterChecklist = {'General Cleaning': [{ cleaned: false, notes: '', name: 'Empty and sanitize trash bins' },{ cleaned: false, notes: '', name: 'Clean mirrors and windows' },],'Home Exterior': [{ cleaned: false, notes: '', name: 'Wipe and clean all furniture' },{ cleaned: false, notes: '', name: 'Empty the trash bins' }]}
const SaveTaskDetails = (name, notes, category) => {
if (!masterChecklist[category]) {
masterChecklist[category] = []
}
masterChecklist[category].push({ name, notes, cleaned: false })
}
SaveTaskDetails('Dust', 'Make sure to get the shelves', 'General Cleaning')
SaveTaskDetails('Dust', 'Make sure to get the shelves', 'New Category')
console.log(masterChecklist)
You should check if the category exists, if not you should assign an empty array and add into it.(I assumed on my code that the category does not exist because it gives an error when the category does not exist.)(By the way I highly recommend you to use const and let instead of var)
You Should Not Use Spaces In Object Key, use _ instead
you can check your variable before doing any operation with typeof operator
example
var masterChecklist = {
"General Cleaning":
[
{cleaned: false, notes: "", name: 'Empty and sanitize trash bins'},
{cleaned: false, notes: "", name: 'Clean mirrors and windows'},
],
"Home Exterior":
[
{cleaned: false, notes: "", name: 'Wipe and clean all furniture'},
{cleaned: false, notes: "", name: 'Empty the trash bins'},
],
}
SaveTaskDetails("Dust", "Make sure to get the shelves", "General Cleaning")
SaveTaskDetails("Dust", "Make sure to get the shelves", "New Category")
function SaveTaskDetails(name, notes, category) {
var newTask = {
name: name,
notes: notes,
cleaned: false
}
var selectedCatg = typeof masterChecklist[category] == "undefined"?masterChecklist[category] = []:masterChecklist[category]
selectedCatg.push(newTask)
}
console.log(masterChecklist);

Search object within object and get the key

I have an object router shown below. lets say I have another var x = "/podcast" and I want to find which key this variable x would reside. For example in this case I want to return the value "M2"
How can I search this object router and it's sub-objects to return the appropriate key?
Thanks!
var router = {
M1: {
url: "/",
description: "",
title: "",
image: "",
},
M2: {
url: "/podcast",
description: "",
title: "",
image: "",
},
M3: {
url: "/about",
description: "",
title: "",
image: "",
},
};
You can use Object.keys() to get Array of object keys then .filter(), here is a working snippet:
const search = '/podcast';
const router = {
M1: {
url: "/",
description: "",
title: "",
image: ""
},
M2: {
url: "/podcast",
description: "",
title: "",
image: ""
},
M3: {
url: "/about",
description: "",
title: "",
image: ""
}
};
const foundElement = Object.keys(router).filter((el) => router[el].url === search);
console.log(foundElement[0]);
To get your keys you use Object.keys(object)
To search the key you can use filter() or find().
To apply the condition you define callback function inside filteror find.
In my case, I used find function :
const foundElement = (router, searchableValue) => {
const founded = Object.keys(router).find(
(value) => router[value].url === searchableValue
);
return founded === undefined ? "Key not found" : founded;
};
const searchableValue = "/podcast";
console.log(foundElement(router, searchableValue));

forEach nested to match

Here i made a code.
let StaffParsed = JSON.parse(params.StaffJson);
console.log(StaffParsed)
Here is the result below fo console log.
Object
cellPhoneNo: "1234567890"
createdBy: "1"
createdDate: "2020-05-09T17:26:31.743"
email: "ravi#email.com"
fax: "1234567890"
firstName: "Ravi"
id: 1004
lastName: "Nikam"
phoneNo: "1234567890"
profilePic: ""
sendEmail: false
sendPhone: false
status: "3"
title: "Mr."
type: "2"
updatedBy: "1"
updatedDate: null
username: "ravi109"
__proto__: Object
I have this model created here is the code below.
public StaffModel : Staff = new Staff();
console.log(this.StaffModel);
Its console log result is below.
Staff
CellPhoneNo: 0
CnfPassword: ""
CreatedBy: ""
CreatedDate: null
Email: ""
Fax: 0
FirstName: ""
FormStaffGroup: FormGroup {validator: null, asyncValidator: null, pristine: true, touched: false, _onCollectionChange: ƒ, …}
Id: null
LastName: ""
Password: ""
PhoneNo: 0
ProfilePic: ""
SendEmail: false
SendPhone: false
Status: "0"
Title: ""
Type: "0"
UpdatedBy: ""
UpdatedDate: null
UserName: ""
__proto__: Object
enter code here
Now i want to match with the above first object list with the second list and update the second list model, so far i have tried this code.
Object.keys(StaffParsed).forEach(function(keyParsed) {
Object.keys(this.StaffModel).forEach((keyModel: string) => {
if(keyParsed == keyModel){
keyParsed = this.StaffModel[keyModel];
}
});
});
But in return, it shows error like this .
Your problem is this part:
... .forEach(function(keyParsed) {
Object.keys(this.StaffModel)
this does not propagate into functions like that. As such, the this inside the function has a different value from the this in the outside function.
If you want the function to inherit the this of the outside scope, use an arrow function instead. ((keyParsed) => { instead of function(keyParsed) {)
In your code this in this.StaffModel[keyModel] may refer to the function not global.
Try this:
let that = this;
Object.keys(StaffParsed).forEach(function (keyParsed) {
Object.keys(that.StaffModel).forEach((keyModel: string) => {
if (keyParsed == keyModel) {
keyParsed = that.StaffModel[keyModel];
}
});
});

Categories

Resources