简体   繁体   中英

Javascript remove keys from nested arrays

I am retrieving data from mysql and want to save each row of data in localStorage as array. The following is my nested array received at javascript end.

arr = [{image_id: "80", imagename: "Image1",firstx: "267", firsty: "403"}, 
      {image_id: "80", imagename: "Image1",firstx: "320", firsty: "470"}, 
      {image_id: "80", imagename: "Image2",firstx: "126", firsty: "237"}
       ]

From this I want to remove the image_id, imagename, firstx and firsty and return a result that is an array and contains only the values of each array. The desired output is

newarr =[[80,Image1,267,403],[80,Image1,320,470],[80,Image2,126,237]]

I have done the following:

var newarr = [];
for (var i = 0, l = arr.length; i < l; i++) {
    var keys = Object.keys(arr[i]);
    for (var j = 0, k = keys.length; j < k; j++) {
        newarr.push(arr[i][keys[j]]);
        }
}

console.log(newarr)

This returns each element of as an array. The resultant array will be pushed to localStorage as a nested array.

I'm guessing you want an array and not an object - map by Object.values :

 const arr = [{image_id: "80", imagename: "Image1",firstx: "267", firsty: "403"}, {image_id: "80", imagename: "Image1",firstx: "320", firsty: "470"}, {image_id: "80", imagename: "Image2",firstx: "126", firsty: "237"} ]; console.log(arr.map(Object.values)); 

var newarr = [];
for (var i = 0, l = arr.length; i < l; i++) {
    var keys = Object.keys(arr[i]);
    newarr[i] = [];
    for (var j = 0, k = keys.length; j < k; j++) {
        newarr[i].push(arr[i][keys[j]]);
        }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM