Home > Net >  Extract value from array of objects [duplicate]
Extract value from array of objects [duplicate]

Time:09-17

So I have this array of objects:

[ { type: 'month', value: '9' },
  { type: 'day', value: '11' },
  { type: 'year', value: '2021' },
  { type: 'hour', value: '7' },
  { type: 'minute', value: '35' },
  { type: 'second', value: '07' }  ]

I need a way to extract the value 9 using the search term month. Sure I could use:

var myObjects = [ 
  { type: 'month', value: '9' },
  { type: 'day', value: '11' },
  { type: 'year', value: '2021' },
  { type: 'hour', value: '7' },
  { type: 'minute', value: '35' },
  { type: 'second', value: '07' }  
] ;

console.log(myObjects[0]["value"]);

Problem is , this is really not using a search term, and I'm in a situation where the date format can change from en_GB to en_US and other complicated time formats which will make the month switch position to [1], [2] or [3].

CodePudding user response:

Using Array#find:

const data = [ { type: 'month', value: '9' }, { type: 'day', value: '11' }, { type: 'year', value: '2021' }, { type: 'hour', value: '7' }, { type: 'minute', value: '35' }, { type: 'second', value: '07' } ];

const { value } = data.find(({ type }) => type === 'month') || {};

console.log(value);

CodePudding user response:

And probably it will be convenient to convert the array of objects into a single object. It can be done this way:

var arr = [
    { type: 'month',  value: '9'   },
    { type: 'day',    value: '11'  },
    { type: 'year',   value: '2021'},
    { type: 'hour',   value: '7'   },
    { type: 'minute', value: '35'  },
    { type: 'second', value: '07'  }
]

const arr_to_obj = arr => {
    var obj = {};
    for (var a of arr) obj[a.type] = a.value;
    return obj;
}

var date = arr_to_obj(arr); // { month:9, day:11, year:2021, ... }

console.log(date.month); // 9
console.log(date.day);   // 11
console.log(date.year);  // 2021
console.log(date.hour);  // 7     ...etc

CodePudding user response:

One more variant:

var arr = [{ type: 'month', value: '9' },
  { type: 'day', value: '11' },
  { type: 'year', value: '2021' },
  { type: 'hour', value: '7' },
  { type: 'minute', value: '35' },
  { type: 'second', value: '07' }];

// var month = arr.filter(x => x.type == 'month')[0].value; // less efficient

var month = arr.find(x => x.type == 'month').value; // more efficient

console.log(month) // 9

  • Related