Home > OS >  keep array order when getting values from json
keep array order when getting values from json

Time:06-06

For input of var idx = [4, 6, 5]:

i: 0 id: 4 rating: 999
i: 2 id: 5 rating: 333
i: 1 id: 6 rating: 666

Desired result:

i: 0 id: 4 rating: 999
i: 1 id: 6 rating: 666
i: 2 id: 5 rating: 333

var data = [{
    "id": 1,
    "rating": 55
  },
  {
    "id": 2,
    "rating": 22
  },
  {
    "id": 3,
    "rating": 111
  },
  {
    "id": 4,
    "rating": 999
  },
  {
    "id": 5,
    "rating": 333
  },
  {
    "id": 6,
    "rating": 666
  }
];

var idx = [4, 6, 5];

$.each(data, function() {
  for (var i = 0; i < idx.length;   i) {
    if (idx[i] == this.id) {
      console.log('i: '   i   ' id: '   this.id   ' rating: '   this.rating);
    }
  }
});

CodePudding user response:

Your problem solves by Array.map Just map your idx values:

var data = [{
    "id": 1,
    "rating": 55
  },
  {
    "id": 2,
    "rating": 22
  },
  {
    "id": 3,
    "rating": 111
  },
  {
    "id": 4,
    "rating": 999
  },
  {
    "id": 5,
    "rating": 333
  },
  {
    "id": 6,
    "rating": 666
  }
];

var idx = [4, 6, 5];
var mappedData = idx.map(function(idx) {
  return data.find(function(dataItem) {
    return dataItem.id === idx
  })
})
mappedData.forEach(function(v) {
  console.log('id: '   v.id   ' rating: '   v.rating);
})

CodePudding user response:

You were just looping with the wrong list :)

var data = [{
    "id": 1,
    "rating": 55
  },
  {
    "id": 2,
    "rating": 22
  },
  {
    "id": 3,
    "rating": 111
  },
  {
    "id": 4,
    "rating": 999
  },
  {
    "id": 5,
    "rating": 333
  },
  {
    "id": 6,
    "rating": 666
  }
];

var idx = [4, 6, 5];

idx.forEach((id, index) => {
  const myData = data.find(x => x.id == id);
  console.log(`i:${index} id:${myData.id} rating: ${myData.rating}`)
});

enter image description here

CodePudding user response:

Try the following:

var data = [{
    "id": 1,
    "rating": 55
  },
  {
    "id": 2,
    "rating": 22
  },
  {
    "id": 3,
    "rating": 111
  },
  {
    "id": 4,
    "rating": 999
  },
  {
    "id": 5,
    "rating": 333
  },
  {
    "id": 6,
    "rating": 666
  }
];

var idx = [4, 6, 5];
for (let i = 0; i < idx.length; i  ) {
  const rating_ind = data.findIndex(e => e.id == idx[i])
  if (rating_ind > -1) {
    console.log('i: '   i   ' id: '   idx[i]   ' rating: '   data[rating_ind].rating);
  }
}

  • Related