0

I would like to know/retrieve/return the value of short_name (example 123) if i have the value of type (example street_number) as information

Array of object :

address = [
    {
        'short_name': '123',
        'type': 'street_number'
    },
    {
        'short_name': 'principal'
        'type': 'route'
    },
    {
        'short_name': 'Washington'
        'type': 'city'
    }
]

I tried mapping, filtering, valueOf(), includes('street_number'), Object.entries, chaining those method, etc.

I would like to put the result in a variable so i can use it later on.

const part_of_address = ... ... ...

3 Answers3

0

You basically want to filter the address based on the type you have.

you can try:

const filtered_data = address.filter((add) => add.type == 'street_number')

if(filtered_data.length){ // This will check if filtered_data is empty
  return filtered_data[0].short_name
}else{
  return ""
}
SouLNex
  • 9
  • 1
0

const address = [
{
    short_name: '123',
    type: 'street_number'
},
{
    short_name: 'principal',
    type: 'route'
},
{
    short_name: 'Washington',
    type: 'city'
}
];

function get(k){
 return address.find(a=>a.type==k)?.short_name
}

console.log(get("city"),get("street_number"),get("wrong_key"));
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0
const address = [
{
    short_name: '123',
    type: 'street_number'
},
{
    short_name: 'principal',
    type: 'route'
},
{
    short_name: 'Washington',
    type: 'city'
}
];
function find(typee) {
var count = 0 ;
    for (var i = 0; i< address.length; i++) {
if(address[i].type == typee) {
console.log(address[i].short_name);
count++;
} 
}
if(count == 0) {
console.log("item not found");
}
}