简体   繁体   中英

How to check if key of object in array has specific value in javascript

Is it possible to check if an object in an array has a specific Date value in the following data format?

I have an array like this for example

[
  {
    date: '2020-05-03',
    items: [{}...]
  },
  ...
]

-> In the above array, I want to check if any object in the array has '2020-05-03' as the date value.

And I want to find out if an object with Date is??

I tried the following, but this only confirms that it has a 'date' as the key, and I couldn't compare values.

const existsDate = _.find(prev, 'date');

I also want to push an item to the items of the object containing that date if a date already exists.

If not, i need to create a new date object.

You can make use of Array.prototype.find and do a string comparison

var arr = [
  {
    date: '2020-05-03',
    items: [{}...]
  },
]

const obj = arr.find(item => item.data === '2020-05-03');

EDIT: Since you want to update the existing array, you would need to make use of slice with findIndex to update array

var arr = [
      {
        date: '2020-05-03',
        items: [{}...]
      },
    ]
    const newItem = {};
    const index= arr.findIndex(item => item.data === '2020-05-03');
    if(index > -1) {
       arr = [...arr.slice(0, index), {...arr[index], items: arr[index].items.concat(newItems), ...arr.slice(index + 1)}
    } else {
      arr.push({data: new Date(), items: [newItem]})
    }

You can use, Array find() , some() to get/check the required conditions, for example:

 const arr = [ { date: '2020-05-03', items: [{}] }, { date: '2020-05-02', items: [{}] } ] function checkAndAdd(date) { const res = arr.find(ob => ob.date === date); // console.log(res); // based on the added comments. // if date is found, push something to the items, list: if (res) { res.items.push('Hello'); } else { arr.push({ date, items: [{}] }) } console.log('finalArray', arr); } checkAndAdd('2020-05-03'); checkAndAdd('2020-05-06');

you caan use filter or find function

let arr = [
    {data:'2020-05-23'},
    {data:'2020-06-23'},
    {data:'2020-07-23'}
]

let find = arr.find( (val) => val.data == '2020-06-23')

console.log(find)

I'm not sure what exactly you are looking to do but his code iterates through the array of objects and checks against the date variable. It outputs the index (i).

let date = "2020-05-03"

const array = [

{   date: "2020-05-01"   },   
{   date: "2020-05-02"   },   
{   date: "2020-05-03",   }, 

]


for(let i = 0 ; i < array.length ; i ++) {   
    if(array[i].date === date) {
        console.log(i);   } 
    else {
        console.log("Date not in array");   
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM