I may have overlooked a topic with the same question. But i can't seem to figure it out. I would like to remove the last to items in the column. Tried a forEach but it wouldn't work for me, it deletes the complete first column of myArr (for example). Maby instead of delete a Slice?
For example i have this JSON array (myArr):
let myArr = JSON.parse(this.responseText);
let myColumnYears = Object.keys(myArr);
let myColumnInhabitants =
Object.values(myArr[0]);
myArr.forEach(function() {
delete myColumnYears[0];
});
[
{
"1996": "7959017",
"1997": "7968041",
"1998": "7976789",
"1999": "7992324",
},
{
"1996": "10156637",
"1997": "10181245",
"1998": "10203008",
"1999": "10226419",
},
{
"1996": "7071850",
"1997": "7088906",
"1998": "7110001",
"1999": "7143991",
}
]
And i would like to remove the last 2 objects of each array so the result becomes:
[
{
"1996": "7959017",
"1997": "7968041",
},
{
"1996": "10156637",
"1997": "10181245",
},
{
"1996": "7071850",
"1997": "7088906",
}
]
I'm missing being a little more specific i guess.
You can iterate over array using .map()
, pick the properties you are interested in and return them as object.
let data = [ {"1996": "7959017", "1997": "7968041", "1998": "7976789","1999": "7992324"}, {"1996": "10156637", "1997": "10181245", "1998": "10203008", "1999": "10226419" }, {"1996": "7071850", "1997": "7088906", "1998": "7110001", "1999": "7143991" } ]; let result = data.map(o => ({"1996": o["1996"], "1997": o["1997"]})); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
What happens if there are more key-pair values in the objects? You will need to modify the map
function.
To avoid this, you can use another way to solve this problem. Try adding more key-value pairs in your objects, this code will always delete the last two key-value pairs.
let data = [ {"1996": "7959017", "1997": "7968041", "1998": "7976789","1999": "7992324"}, {"1996": "10156637", "1997": "10181245", "1998": "10203008", "1999": "10226419" }, {"1996": "7071850", "1997": "7088906", "1998": "7110001", "1999": "7143991" } ]; data.forEach((element, index) => { const keys = Object.keys(element); delete element[keys[keys.length - 1]]; delete element[keys[keys.length - 2]]; }); console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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.