Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

array object make api format javascript

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);
 Run code snippetHide results
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #array #object #api #format #javascript
ADD COMMENT
Topic
Name
6+5 =