Javascript数组验证

时间:2018-02-05 04:17:55

标签: javascript arrays

我有两个数组,一个是普通的字符串数组,另一个是对象数组,如下所示:

listOfObjects[
  { "name": "A", "data": "[{'value1':'1','value2':'2'}]" },
  { "name": "B", "data": "[{'value1':'','value2':''}]" }
]
stringArray["A","B","C"]

如何比较这两个数组并返回listOfObjects中不存在的stringArray。以此为例,它将返回" C"因为它在listOfObjects中不存在。

此外,我还希望它检查listofObjects并在data.value1或data.value2为空时返回名称。例如,返回" B"。

1 个答案:

答案 0 :(得分:0)

要获取stringArraylistOfObjects中不存在的array#find中的值,您可以使用array#find并迭代每个值并使用listOfObjects检查它是否存在存在于var listOfObjects = [{ "name": "A", "data": "[{'value1':'1','value2':'2'}]" }, { "name": "B", "data": "[{'value1':'','value2':''}]" } ], stringArray = ["A", "B", "C"], result = stringArray.find(word => !listOfObjects.find(({name}) => name === word)); console.log(result);中。



array#filter




要查找数据值中包含空字符串的所有对象,可以使用listOfObjects遍历stringArray并检查它是否存在于var listOfObjects = [ { "name": "A", "data": "[{'value1':'1','value2':'2'}]" }, { "name": "B", "data": "[{'value1':'','value2':''}]" } ], stringArray = ["A","B","C"], result = listOfObjects.filter(({name, data}) => { return stringArray.includes(name) && JSON.parse(data.replace(/'/g,'"')).every(obj => Object.keys(obj).every(key => !obj[key])); }).map(({name}) => name); console.log(result);中,然后您可以解析数据并检查每个值是否为空字符串。



.box-foto2-content {
    display: flex;
    //Other css...
}

.text1-wrapper {
    margin: 0 auto;
    //Other css...
}