如何在NodeJS中的JSON中更新值并过滤以排除值? [英] How to update value in JSON in NodeJS and filter to exclude values?

查看:180
本文介绍了如何在NodeJS中的JSON中更新值并过滤以排除值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var data = [{
   "description" : "sample",
   "link" : "mylink",
   "id" :"1",
   "deviceName":"mydevice1"
},
{
   "description" : "sample",
   "link" : "mylink",
   "id" :"1",
   "deviceName":"mydevice1"
},
{
   "description" : "sample",
   "link" : "mylink",
   "id" :"",
   "deviceName":""
}]

如何在JSON对象中将"deviceName"=""为空的deviceName更新为novaluespecified?

注意

最初它是一个巨大的数组,所以我无法为1个单一索引做

我还需要过滤掉所有名为device1的设备,并且不将其包含在我搜索的最终JSON中,发现.filter包含但未找到排除某些东西的功能

编辑

我不希望使用jquery,并且如果可能的话,请完全使用NodeJS.

如果我绝对需要使用jQuery,我也不介意

解决方案

您可以在下面尝试希望对您有所帮助.首先,我已使用

var data = [{
   "description" : "sample",
   "link" : "mylink",
   "id" :"1",
   "deviceName":"mydevice1"
},
{
   "description" : "sample",
   "link" : "mylink",
   "id" :"1",
   "deviceName":"mydevice1"
},
{
   "description" : "sample",
   "link" : "mylink",
   "id" :"",
   "deviceName":""
}]

How do i update deviceName where it is empty that is "deviceName"="" to novaluespecified in my JSON object ??

Note

originally it is a huge array so i can't do it for 1 single index

Also i need to filter out all devices named device1 and NOT include that in my final JSON i searched around and i found .filter for including but could not find a function for excluding something

EDIT

I would prefer not to use jquery and if possible do it with NodeJS fully.. any help is appreciated :)

and i don't mind using jquery if its absolutely required

解决方案

You can try below Hope it helps.First I have used Array.map to transform the value where deviceName is empty string.Next I have used Array filter with indexOF to filter out the values.

var data = [{
    "description": "sample",
    "link": "mylink",
    "id": "1",
    "deviceName": "mydevice1"
  },
  {
    "description": "sample",
    "link": "mylink",
    "id": "1",
    "deviceName": "mydevice1"
  },
  {
    "description": "sample",
    "link": "mylink",
    "id": "",
    "deviceName": ""
  }
]

let _res = data.map(ele => {
  if (ele.deviceName == "") {

    ele.deviceName = "novaluespecified"
  }
  return ele;

})


console.log(_res)

// filtering out device1


var data2 = [{
    "description": "sample",
    "link": "mylink",
    "id": "1",
    "deviceName": "mydevice1"
  },
  {
    "description": "sample",
    "link": "mylink",
    "id": "1",
    "deviceName": "mydevice1"
  },
  {
    "description": "sample",
    "link": "mylink",
    "id": "",
    "deviceName": ""
  }
]

let _res1 = data2.filter(ele => {

  if (ele.deviceName.indexOf('device1') == -1) {
    return ele;
  }



})
console.log(_res1)

这篇关于如何在NodeJS中的JSON中更新值并过滤以排除值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆