-2

I want to have an array that elements inside look like this:

Array(3)
0: name: true;
1: price : false;
2: stock: true;
length: 3

So when I need to get any element, I could get it by calling property name like:

if(array[name] == false)
{
 //do smth
}  

How to achieve this using jquery?

Cavid
  • 125
  • 13
  • Did `name: true` and similars are object? – Kévin Bibollet Jun 07 '19 at 12:18
  • 4
    you need an object for this kind of check. – Nina Scholz Jun 07 '19 at 12:18
  • `array[name]` seems like accessing an object property, unless `name` represents an index in the array... in any case `array[index][name]` would be more realistic. A [Minimal, Reproducible Example](http://stackoverflow.com/help/minimal-reproducible-example) showing what you're trying to achieve and where you're struggling would be very welcome. – lealceldeiro Jun 07 '19 at 12:19
  • 2
    There's not jQuery required here. A POJS object has this behaviour out of the box. – Rory McCrossan Jun 07 '19 at 12:21
  • 2
    1) You need object from this not array. 2) This will be same for jquery too. You can't apply any jquery feature to shorten it. – Maheer Ali Jun 07 '19 at 12:21
  • Why would you want this "using jQuery"? jQuery *is* JavaScript. – VLAZ Jun 07 '19 at 12:22
  • @lealceldeiro that would be long if I explain but this all stuff inside an array should refer to html input elements inside a form in order to make further validation check. – Cavid Jun 07 '19 at 12:29

1 Answers1

1

jQuery will not help you with what you want to achieve.

You can affect the wanted property thanks to the following: yourArray['yourProperty'] = 'yourValue';.

const arr = [];

arr['name'] = true;
arr['price'] = true;
arr['stock'] = false;

// Access properties like:
console.log(arr['name']);

if (arr['name'] === true) {
  console.log('name is true');
}

However, be aware that the length of you array will stay at 0. So you will not be able to loop through it with a simple for statement neither a for...of statement.


Note: I suggest you to use objects instead, as arrays are not made to have string properties.

Please, read the link @GalAbra give us in the comments for further details.

const obj = {
  name: true,
  price: true,
  stock: false
};

// Access properties like:
console.log(obj.name);

if (obj.name === true) {
  console.log('name is true');
}
Kévin Bibollet
  • 3,573
  • 1
  • 15
  • 33