Проверочное значение равно конкретному значению в массиве - javascript - PullRequest
0 голосов
/ 03 мая 2018

У меня есть объект ниже

members
    {
        [
            age:30,
            list: [
                "PRICE",
                "LIST",
                "COUNTRY"
            ]
        ]
    },
    {
        [
            age:31,
            list: [
                "PRICE"
            ]
        ]
    },
    {
        [
            age:31,
            list: [
                "LIST"
            ]
        ]
    }

Мне нужно проверить, равны ли значения массива конкретному значению.

Мне нужно проверить, имеет ли list значение PRICE или list, значение COUNTRY или list, значение PRICE,LIST,COUNTRY.

В настоящее время я использую includes, который проверяет наличие значения. Но мне нужно проверить точное значение

Array.isArray(members.list.map(message, index){
        if(message.includes("LIST"))
        {

        }
        if(message.includes("PRICE"))
        {

        }
         if(message.includes("PRICE") && message.includes("LIST") && message.includes("COUNTRY"))
        {
            //message.includes("PRICE") and ("LIST") is already executed, so this will execute again. But i need to execute the complete condition combination.
        }
    })

Как этого добиться?

Ответы [ 3 ]

0 голосов
/ 03 мая 2018

Вы можете создать функцию фильтра и использовать ее для Array.prototype.filter

const members = [
  {
    age: 30,
    list: ["PRICE","LIST","COUNTRY"]
  },
  {
    age: 31,
    list: ["PRICE"]
  },
  {
    age: 31,
    list: ["LIST"]
  },
  {
    age: 88,
    list: ["not this one"]
  },
  {
    age: 88,
    list: ["not this one","COUNTRY","NOTPRICEORLIST"]
  }
]

const getList = o => (o&&o.list) || [];//get list member from o or returns empty array
const contains = needle => haystack => haystack.includes(needle);//check if haystack contains needle
const containsAll = needles => haystack => needles.reduce(
  (result,needle)=>result && haystack.includes(needle),
  true
);
const countryOrPriceOrPriceListCountry = haystack =>
  contains("PRICE")(haystack) || contains("LIST")(haystack)
  //this is pointless, would already be true because it contains price or country
  // || containsAll(["PRICE","LIST","COUNTRY"])(haystack);

const filter = getter => comparer => item =>//get something from item (list) and send to compare function
  comparer(getter(item));

console.log(
  members.filter(filter(getList)(countryOrPriceOrPriceListCountry))
);

Или, может быть, вы искали следующее:

const members = [
  {
    age: 30,
    list: ["PRICE","LIST","COUNTRY"]
  },
  {
    age: 31,
    list: ["PRICE"]
  },
  {
    age: 32,
    list: ["LIST"]
  },
  {
    age: 88,
    list: ["not this one"]
  },
  {
    age: 89,
    list: ["not this one","COUNTRY","NOTPRICEORLIST"]
  }
]

const getList = o => (o&&o.list) || [];//get list member from o or returns empty array
const contains = needle => haystack => haystack.includes(needle);//check if haystack contains needle
const containsAll = needles => haystack => needles.reduce(
  (result,needle)=>result && haystack.includes(needle),
  true
);
const countryOrPrice = haystack =>
  contains("PRICE")(haystack) || contains("LIST")(haystack)
const countryListAndPrice = containsAll(["PRICE","LIST","COUNTRY"]);

members.map(
  item=>[item,countryOrPrice(getList(item))]//see if item has country or price
).map(
  ([item,hasCountryOrPrice])=>[
    item,
    hasCountryOrPrice,
    // will check for country list and price only if has country or price 
    hasCountryOrPrice && countryListAndPrice(getList(item))
  ]
).forEach(
  ([item,hasCountryOrPrice,countryListAndPrice])=>
    console.log(
      "item age:",
      item.age,
      "has country or price:",
      hasCountryOrPrice,
      "has country list and price:",
      countryListAndPrice
    )
);
0 голосов
/ 03 мая 2018

Надеюсь, это поможет

var members = [
	{ age: 30, list: ["PRICE", "LIST", "COUNTRY"] },
	{ age: 31, list: ["PRICE"] },
	{ age: 31, list: ["LIST"] }
];
members.forEach((val,key)=>{
	if(Array.isArray(val.list)){
		if(val.list.indexOf('PRICE') > -1 || val.list.indexOf('COUNTRY') > -1 || (val.list.indexOf('PRICE') > -1 && val.list.indexOf('COUNTRY') > -1 && val.list.indexOf('LIST') > -1)){
			console.log(val)
		}
	}
});
0 голосов
/ 03 мая 2018

Ваша задача - пройти через все возможные условия if.
Таким образом, вы не должны делать return в проверке состояния.
Вы можете сохранить результат и переопределить его всякий раз, когда он соответствует условию. Надежда может помочь.
Также есть некоторые проблемы вашего происхождения членов Object. Также исправлено в следующей демонстрации.

let members = [
	{ age: 30, list: ["PRICE", "LIST", "COUNTRY"] },
	{ age: 31, list: ["PRICE"] },
	{ age: 31, list: ["LIST"] }
];

   Array.prototype.inArray = function () {
var message = this;
if (message.includes("PRICE") && message.includes("LIST") && message.includes("COUNTRY")) {
	return "contains PRICE, LIST and COUNTRY";
}
if (message.includes("PRICE") && message.includes("LIST") ) {
	return "contains PRICE and LIST ";
}
if (message.includes("PRICE") &&  message.includes("COUNTRY")) {
	return "contains PRICE and COUNTRY";
}
if (message.includes("LIST") && message.includes("COUNTRY")) {
	return "contains LIST and COUNTRY";
}
if (message.includes("LIST")) {
	return "contains LIST";
}
if (message.includes("PRICE")) {
	return "contains PRICE";
}
if (message.includes("LIST")) {
	return "contains LIST";
}
}

for (let member of members) {
	console.log(member.list.inArray());
}
...