I have a JSON array like this:
[{Company:"", FirstName:"John", SecondName:"Smith", ID:"2345"},
{Company:"SomeComp", FirstName:"", SecondName:"Kane", ID:"4363"},
{Company:"Random", FirstName:"Tom", SecondName:"", ID:"6454"}]
I want to parse this and create a new array of objects which only have non-blank attributes without IDs, ie:
[{FirstName:"John", SecondName:"Smith"},
{Company:"SomeComp", SecondName:"Kane"},
{Company:"Random", FirstName:"Tom"}]
What is the best way of doing this in Javascript?
You can use map
The map() method creates a new array with the results of calling a provided function on every element in this array.
var companies = [{Company:"", FirstName:"John", SecondName:"Smith", ID:"2345"}, {Company:"SomeComp", FirstName:"", SecondName:"Kane", ID:"4363"}, {Company:"Random", FirstName:"Tom", SecondName:"", ID:"6454"}]; // This returns a new array var newArray = companies.map(function(item) { var obj = {}; for(var prop in item) { if (item[prop] !== "" && prop !== "id" ) { obj[prop] = item[prop]; }; } return obj; }); console.log(newArray);
This should do it
var input = JSON.parse("<YOUR JSON HERE>");
var output = [];
input.forEach(function(item) {
delete item.ID;
for (var prop in item) {
if (item.hasOwnProperty(prop) && item[prop] === "") {
item[prop] = undefined;
}
}
output.push(item);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.