我正在使用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存储在文本字段中)
最佳答案
带有香草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)
关于javascript - 在迭代时在对象上设置属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52500510/