在迭代时在对象上设置属性

时间:2018-09-25 14:22:56

标签: javascript jquery vue.js

我正在使用Laravel(后端)和Vue.js制作SPA。我有以下数组:

accessArray:

["BIU","CEO","Finance","HRD","Group"]

访问权限:

["BIU","Group"]

我想将access数组与accessArray数组进行比较,如果有匹配项来更改记录(在accessArray中)并添加一个true值否则添加一个false值。我正在Vue方法中执行此操作。

...到目前为止,我得到了:

var foo = ["BIU","CEO","Finance","HRD","Group"];
var bar = ["BIU","Group"];

$.each(bar, function (key, value) {
    if ($.inArray(value, foo) != -1) {
        var position = $.inArray(value, foo);
        console.log(value + ' is in the array.  In position ' + position);
        foo[position] = {name: value, checked: true};
    }
});

将其输出到控制台:

BIU is in the array.  In position 0
Group is in the array.  In position 4

这在Vue中:

[
{"name":"BIU","checked":true},
"CEO",
"Finance",
"HRD",
{"name":"Group","checked":true}
]

我想要实现的输出如下:

[
{"name":"BIU","checked":true},
{"name":"CEO","checked":false},
{"name":"Finance","checked":false},
{"name":"HRD","checked":false},
{"name":"Group","checked":true}
]

任何帮助将不胜感激,我已经在SO上研究了许多类似的问题,但似乎找不到任何类似的方法。我还尝试在最后添加else语句,但我(认为)我正在将其转换为对象,因此似乎无法正常工作。

编辑:

foo中的数据来自Laravel配置设置,因此有些动态

栏中的数据是从Laravel ORM接收的JSON(其json存储在文本字段中)

4 个答案:

答案 0 :(得分:6)

使用香草javascript的选项:

var foo = ["BIU","CEO","Finance","HRD","Group"];
var bar = ["BIU","Group"];

var result = foo.map(name => {
    var checked = bar.indexOf(name) !== -1
    return { name, checked }
})

console.log(result)

答案 1 :(得分:4)

您可以使用Array#map遍历数组并构造一个新数组,方法是通过Array#includes检查另一个数组中是否存在值

const accessArray = ["BIU","CEO","Finance","HRD","Group"];
const access = [ "BIU", "Group" ];

const result = accessArray.map( a => ({ name: a, checked: access.includes(a)}) ) ;

console.log(result);

注意:当使用箭头函数并且要返回对象时,需要将对象文字括在()中,否则它将被解释为代码块。

答案 2 :(得分:0)

使用reduce并在化简回调中检查accessArrayaccess中是否都存在该项目。创建一个对象,两个数组中都存在的项目将checked的值设置为true或false

let arr1 = ["BIU", "CEO", "Finance", "HRD", "Group"]
let arr2 = ["BIU", "Group"];

let k = arr1.reduce(function(acc, curr) {
  let obj = {}
  if (arr2.includes(curr)) {
    obj.name = curr;
    obj.checked = true
  } else {
    obj.name = curr;
    obj.checked = false
  }
  acc.push(obj);
  return acc;


}, []);

console.log(k)

答案 3 :(得分:0)

要获得预期结果,请使用以下选项
1.循环foo数组
2.删除初始if条件-“ if($ .inArray(value,foo)!= -1)”遍历所有
3.对是否已检查-已检查进行条件检查:$ .inArray(value,bar)!== -1吗? true:否

codepen-https://codepen.io/nagasai/pen/GXbQOw?editors=1011

  var foo = ["BIU","CEO","Finance","HRD","Group"];
    var bar = ["BIU","Group"];
    
    $.each(foo, function (key, value) {
        foo[key] = {name: value, checked: $.inArray(value, bar) !== -1 ? true : false};
    });
    
    console.log(foo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

选项2
不使用jquery并使用简单的forEach遍历foo

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

      var foo = ["BIU","CEO","Finance","HRD","Group"];
      var bar = ["BIU","Group"];

foo.forEach((v,i) => foo[i] = {name: v , checked : bar.includes(v)})
console.log(foo);