删除数组中的特定名称

时间:2018-11-15 16:32:26

标签: javascript json

userInput

如何从阵列中仅删除汽车信息。

2 个答案:

答案 0 :(得分:0)

const obj = JSON.parse(jsonString);
let yourArray = obj.list;


  let filteredArray = yourArray.filter(elem => elem.name !== "car");

答案 1 :(得分:0)

要获得预期结果,请使用过滤器选项过滤掉与汽车相关的值

var obj = {"list":[ {"name":"car", "status":"Good", "time":"2018-11-02T03:26:34.350Z"}, {"name":"Truck", "status":"Ok", "time":"2018-11-02T03:27:23.038Z"}, {"name":"Bike", "status":"NEW", "time":"2018-11-02T13:08:49.175Z"} ]}

let result = {
  list: []
}
    
result.list.push(obj.list.filter(v => v.name !=='car'))
console.log(result)

codepen-https://codepen.io/nagasai/pen/MzmMQp

选项2:,而不使用OP要求的过滤器

使用简单的for循环获得相同的结果

var obj = {"list":[ {"name":"car", "status":"Good", "time":"2018-11-02T03:26:34.350Z"}, {"name":"Truck", "status":"Ok", "time":"2018-11-02T03:27:23.038Z"}, {"name":"Bike", "status":"NEW", "time":"2018-11-02T13:08:49.175Z"} ]}

let result = {
  list: []
}
    
 for(let i =0; i< obj.list.length; i++){
   if(obj.list[i].name !== 'car' ){
     result.list.push(obj.list[i])   
   }

 } 
console.log(result)