[Vuejs]-Set property on object while iterating

6๐Ÿ‘

โœ…

An option with vanilla 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)
๐Ÿ‘คPsidom

4๐Ÿ‘

You can use Array#map to iterate over the array and construct a new one, by checking if values are present in the other one through 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);

A note: when using an arrow function and you want to return an object, you need to surround the object literal in () otherwise it would be interpreted as a code block.

๐Ÿ‘คVLAZ

0๐Ÿ‘

Use reduce and inside the reduce call back check if the item is present in both accessArray & access . Create an object and the item present in both array set the value of checked to true or 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)
๐Ÿ‘คbrk

0๐Ÿ‘

To achieve expected result use below option
1. Loop foo array
2.Remove initial if condition โ€“ โ€œif ($.inArray(value, foo) != -1)โ€ to loop through all
3. Do conditional check for checked โ€“ checked: $.inArray(value, bar) !== -1 ? true : false

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>

Option 2:
Without using jquery and using simple forEach to loop through 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);
๐Ÿ‘คNaga Sai A

Leave a comment