简体   繁体   中英

How to format API JSON response to an array object in JS?

I am creating a dashboard in ReactJS and I am using axios to make API calls.

API Response

const response = {
  users: {
    144: [
      {
        name: "Olivia",
      },
      {
        mode: "c7",
        fkProductsIds: [ 3, 2 ]
      }
    ],
    168: [
      {
        name: "Jill",
      },
      {
        mode: "p9",
        fkProductsIds: [ 1, 4, 5, 3 ]
      }
    ],
    202: [
      {
        name: "David",
      },
      {
        mode: "p9",
        fkProductsIds: [ 5, 1, 2 ]
      }
    ]
  },
  products: [
    { 1: "PSM" },
    { 2: "FP" },
    { 3: "F2" },
    { 4: "Mark4" },
    { 5: "Astrid" },
  ]
}

I want to convert this response to an array so that I can easily use this data to show in a list on UI.

What I already have tried is

render(){

  // --> Logic start
  var data = Object.keys(response.users).map( userId => {
    var tmp = {}
    tmp.id       = userId
    tmp.name     = response.users[userId][0].name
    tmp.mode     = response.users[userId][1].mode
    tmp.products = response.users[userId][1].fkProductsIds
    return tmp
  })
  // <-- Logic end

  return(
    <ul> { data.map(user=><UserRow user={user} />) } </ul>
  )
}

Output

data = [{
    "id": "144",
    "name": "Olivia",
    "mode": "c7",
    "products": [3, 2]
  }, {
    "id": "168",
    "name": "Jill",
    "mode": "p9",
    "products": [1, 4, 5, 3]
  }, {
    "id": "202",
    "name": "David",
    "mode": "p9",
    "products": [5, 1, 2]
}]

Now how to

  1. Sort users by number of products
  2. Convert product ids in product key to object
  3. Sort products key by id

Expected

const data = [
  {
    id  : 168,
    name: "Jill",
    mode: "p9",
    products: [
      { id: 1, name: "PSM"    },
      { id: 3, name: "F2"     },
      { id: 4, name: "Mark"   },
      { id: 5, name: "Astrid" }
    ]
  },
  {
    id  : 202,
    name: "David",
    mode: "p9",
    products: [
      { id: 1, name: "PSM"    },
      { id: 2, name: "FP"     },
      { id: 5, name: "Astrid" }
    ]
  },
  {
    id  : 144,
    name: "Olivia",
    mode: "c7",
    products: [
      { id: 2, name: "FP" },
      { id: 3, name: "F2" },
    ]
  }
]

As you can see, all users are sorted by the number of products they own and objects inside products key of users is also sorted by id .

Update your data object with this code

var data = Object.keys(response.users).map( userId => {
var tmp = {}
tmp.id       = userId
tmp.name     = response.users[userId][0].name
tmp.mode     = response.users[userId][1].mode
tmp.products = response.users[userId][1].fkProductsIds.sort().map((pId) => {
    let ret = {id: '', name: ''};
    ret.id = pId;
    let productById = response.products.filter((productIdx) => pId==Object.keys(productIdx)[0] );

    if(productById && productById.length) {
        ret.name = productById[0][pId];
    }
    return ret;
});
return tmp
})

You could use sort method in combination with map .

 const response = { users: { 144: [ { name: "Olivia", }, { mode: "c7", fkProductsIds: [ 3, 2 ] } ], 168: [ { name: "Jill", }, { mode: "p9", fkProductsIds: [ 1, 4, 5, 3 ] } ], 202: [ { name: "David", }, { mode: "p9", fkProductsIds: [ 5, 1, 2 ] } ] }, products: [ { 1: "PSM" }, { 2: "FP" }, { 3: "F2" }, { 4: "Mark4" }, { 5: "Astrid" }, ] } getProductById = (id) => { var elem = response.products.find(elem => elem[id]); return {id: id, name: elem[id]} } var data = Object.keys(response.users).map( userId => ({ id: userId, name: response.users[userId][0].name, mode: response.users[userId][1].mode, products: response.users[userId][1].fkProductsIds.sort().map(getProductById) })).sort((a, b) => b.products.length - a.products.length) console.log(data);

sort by products length:

 const data = [{ "id": "144", "name": "Olivia", "mode": "c7", "products": [3, 2] }, { "id": "168", "name": "Jill", "mode": "p9", "products": [1, 4, 5, 3] }, { "id": "202", "name": "David", "mode": "p9", "products": [5, 1, 2] }]; data.sort((a,b) => a.products.length - b.products.length); console.log(data)

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