从Typescript中的数组中获取特定的值

时间:2019-01-19 11:09:08

标签: typescript

我正在以数组形式获得响应。我正在操纵它以便从每个数组元素中获取特定的值。

实际回答:

enter image description here

当我这样做

 //carb_value is a array that contain the above response

  var l = this.carbs_value.length;
  for (var i = 0; i < l; i++) {
  console.log(this.carbs_value[i]);
  }

我得到了:

enter image description here

我需要的是,从类似数组的每个元素中选择特定的值

0: { carbs: 30}
1: { carbs: 25}

2 个答案:

答案 0 :(得分:0)

那是因为您正在输出整个记录。您可以执行以下操作(首选forEach进行手动迭代):

this.carbs_value.forEach(record => console.log({ carbs: record.carbs }));

如果要保存到新数组,可以使用map

const filtered = this.carbs_value.map(record => { carbs: record.carbs });
console.log(filtered);

答案 1 :(得分:0)

const carbs_value = [
{ _id : "someval", quantity: 22, item: "val", carbs: 30},
{ _id : "someval", quantity: 22, item: "val", carbs: 3},
{ _id : "someval", quantity: 22, item: "val", carbs: 350},
{ _id : "someval", quantity: 22, item: "val", carbs: 630},
];

const allowed = ['carbs'];

const filtered = carbs_value.map(e=> Object.keys(e)
  .filter(key => allowed.includes(key))
  .reduce((obj, key) => {
    obj[key] = e[key];
    return obj;
  }, {})   );
  
  console.log(filtered);
  
  
console.log("So now you can select an element:");
  
   console.log(filtered[0]);
   console.log(filtered[1]);