Having the following JSON object:
var employees = {
"staff": [{
"firstName": "Tony",
"lastName": "deAraujo",
"age": 99
}, {
"firstName": "John",
"lastName": "Smith",
"age": 33
}, {
"firstName": "Mary",
"lastName": "Adams",
"age": 29
}],
"management": [{
"firstName": "Judy",
"lastName": "Garland",
"age": 43
}]
};
I would like to know if it is possible to display in the same conversion with stringify:
firstName
and lastName
of staff
and age
of management
.
Since I know that it can be done separately like this:
var resultado = JSON.stringify(employees, ["staff", "firstName","lastName"]);
var resultado2 = JSON.stringify(employees, ["management", "age"]);
Try doing the following:
1) var resultado = JSON.stringify(employees, ["staff", "firstName","lastName" ,"management", "age"]);
But it returns firstName
, lastName
, age
both from staff
and from management
.
{"staff":[{"firstName":"Tony","age":99},{"firstName":"John","age":33},{"firstName":"Mary","age":29},{"firstName":"Loren","age":29}],"management":[{"firstName":"Judy","age":43},{"firstName":"Loren","age":29}]}
two)var someString = JSON.stringify(employees, ["staff", "firstName","lastName"],["management", "age"]);
But it returns me alone firstName
andlastName
staff
{"staff":[{"firstName":"Tony","lastName":"deAraujo"},{"firstName":"John","lastName":"Smith"},{"firstName":"Mary","lastName":"Adams"},{"firstName":"Loren","lastName":"Santos"}]}
Expected result:
{"staff":[{"firstName":"Tony","lastName":"resultado"},{"firstName":"John","lastName":"resultado"},{"firstName":"Mary","lastName":"resultado"},{"firstName":"Loren","lastName":"resultado"}],"management":[{"age":"43","age":"23"}}
I guess something like this, I think I'm missing commas and braces.
I think using
JSON.stringify
to do this process this way is overcomplicating. Going through the array you can choose the keys that will be part of your new JSON. (First example)Although if you want you can use the second argument of
JSON.stringify
but instead of passing it an Array, you must pass it a function. In this function (which receives theclave
yvalor
of the object it is converting tostring
) we check the key and format the content ofstaff
ymanagement
so that the objects inside those Arrays contain only the properties we want (Second example)To see the code in ES5 Click here