【问题标题】:how to get boolean value from an array which contains array and objects as elements如何从包含数组和对象作为元素的数组中获取布尔值
【发布时间】:2022-01-11 01:50:25
【问题描述】:

我需要从数组和对象的数组中获取一个布尔值,如下所示

points = [
  [1,2,3,4],
  {a:1, b:2}
]

现在,我从服务器获取了一些数组或对象,

let newVal = [1,2,3,4]
or sometimes 
let newVal = {a: 2, b: 5}  etc

我需要检查它是否存在于points 中,如果不存在则推入它。

 if(!_.some(points, val => _.isEqual(val,newVal))){
    points.push(newVal)
 } else return;

预期结果
如果newVal 存在于points 中,那么我应该得到true 否则false

但如果newVal 是数组,上述_some 总是返回true。

谁能帮帮我。

【问题讨论】:

  • 请添加想要的结果。
  • @NinaScholz 请看一下
  • 尝试points.some(val => _.isEqual(val,newVal)) 而不是_.some(points, val => _.isEqual(val,newVal))。内置的some 应该可以满足您的需求。
  • @user2740650 是的,它正在工作

标签: javascript lodash


【解决方案1】:

如果您依赖lodash 中的isEqual 来确定相等性,则可以使用:

points.some(val => isEqual(val, newVal))

以下示例 sn-p:

<script type="module">

import {isEqual} from 'https://cdn.jsdelivr.net/npm/lodash-es@4.17.21/lodash.min.js';

// returns `true` if value was added, `false` otherwise
function addNewValueIfNotEqual (arr, value) {
  if (arr.some(v => isEqual(v, value))) return false;
  arr.push(value);
  return true;
}

const points = [
  [1,2,3,4],
  {a:1, b:2},
];

const newValues = [
  [1, 2, 3, 4],
  {a: 2, b: 5},
];

for (const value of newValues) {
  const valueAdded = addNewValueIfNotEqual(points, value);
  console.log({value, valueAdded});
}

console.log(points);

</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2021-08-14
    • 2022-01-22
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多