boomchickawawa
boomchickawawa

Reputation: 556

Loop through an object and get all the values of the keys

I am trying to loop through an object and get all the key values that is name and I am doing it in the following way :

var fakeData = {
     "manufacturer": "tesla",
     "cars": [
          {"title": "CALI", "name": "CALI", "type": "string" },
          {"title": "TEXAS", "name": "TEXAS", "type": "string" },
          {"title": "NY", "name": "NY", "type": "string" }
     ],
     "usedCars": [
          {"title": "FL", "name": "FL", "type": "string" }
     ],
}

returnName(fakeData) {
    for (key in fakeData.cars && fakeData.usedCars) {
     //return name property  of cars and usedCars arrays.
     //fakeData is the representation of the req.body data that might 
     //sometimes not necessarily have either cars or usedCars

    }

}

It returns undefined if I do this. Is there any way to fit those conditions in one for loop and get the desired results?

Upvotes: 0

Views: 119

Answers (5)

sofa_maniac
sofa_maniac

Reputation: 1647

This will do the job.

(fakeData.cars?fakeData.cars:[]).concat(fakeData.usedCars?fakeData.usedCars:[]).map(car => car.name)

Output:

["CALI", "TEXAS", "NY", "FL"]

Explanation:

First, we use a conditional to check if faekData.cars actually exists or not. If it does, get the array. If not, return an empty array in its place.

  (fakeData.cars)?fakeData.cars:[]

This translates to: (condition==true)? (do this if true):(do this if false)

If the array does not exist, the condition will not be satisfied. So, the "(do this if false)" part will be executed.

Then, we do the same with the second array. By using "concat", we concatenate both arrays into a single one. Then, we use "map" to transform the whole objects into just the value of the "name" property.

Upvotes: 2

LaytonGB
LaytonGB

Reputation: 1404

Hope this is what you're looking for.

var fakeData = {
     "manufacturer": "tesla",
     "cars": [
          {"title": "CALI", "name": "CALI", "type": "string" },
          {"title": "TEXAS", "name": "TEXAS", "type": "string" },
          {"title": "NY", "name": "NY", "type": "string" }
     ],
     "usedCars": [
          {"title": "FL", "name": "FL", "type": "string" }
     ],
};

[].concat(
    fakeData.cars ? fakeData.cars : [],
    fakeData.usedCars ? fakeData.usedCars : [],
    fakeData.undefinedCars ? fakeData.undefinedCars : [],
).forEach(car => {
    console.log(car.name);
});

For more arrays just add them into the .concat() function separated by a comma:

array1.concat(array2, array3, array4)

Upvotes: 1

Ali Klein
Ali Klein

Reputation: 1908

You could concat the objects you want into an array and map out whatever values you'd like to access. Is that what you're looking for?

const fakeData = {
    manufacturer: 'tesla',
    cars: [
      { title: 'CALI', name: 'CALI', type: 'string' },
      { title: 'TEXAS', name: 'TEXAS', type: 'string' },
      { title: 'NY', name: 'NY', type: 'string' }
    ],
    usedCars: [{ title: 'FL', name: 'FL', type: 'string' }]
  };
  
  const combinedCarData = [...fakeData.cars, ...fakeData.usedCars];
  
  // Map whatever values you would like to access
  
  combinedCarData.map(car => {
    console.log(car.title);
    console.log(car.name);
    console.log(car.type);
  });

Upvotes: 0

jgamesl
jgamesl

Reputation: 296

This should print all the car names

var fakeData = {
     "manufacturer": "tesla",
     "cars": [
          {"title": "CALI", "name": "CALI", "type": "string" },
          {"title": "TEXAS", "name": "TEXAS", "type": "string" },
          {"title": "NY", "name": "NY", "type": "string" }
     ],
     "usedCars": [
          {"title": "FL", "name": "FL", "type": "string" }
     ],
}

var results = [];

function returnNames(){
    for(index in fakeData.cars){
        results.push(fakeData.cars[index].title);
    }
    for(index in fakeData.usedCars){
        results.push(fakeData.usedCars[index].title);
    }
    
    console.log("car names: " + results)
}

Upvotes: 0

zero298
zero298

Reputation: 26867

for (key in fakeData.cars && fakeData.usedCars) doesn't mean "get me the keys in cars and usedCars", it means "get me the keys of the evaluation of cars && usedCars" (which is cars since it's truthy).

Instead, just use a .map and get the names out:

var fakeData = {
     "manufacturer": "tesla",
     "cars": [
          {"title": "CALI", "name": "CALI", "type": "string" },
          {"title": "TEXAS", "name": "TEXAS", "type": "string" },
          {"title": "NY", "name": "NY", "type": "string" }
     ],
     "usedCars": [
          {"title": "FL", "name": "FL", "type": "string" }
     ],
}

/*
This doesn't mean "get me the keys in cars and usedCars"
it means "get me the keys of the evaluation of cars && usedCars"
(which is cars since it's truthy)
returnName(fakeData) {
    for (key in fakeData.cars && fakeData.usedCars) {
     //return name property  of cars and usedCars arrays.
     //fakeData is the representation of the req.body data that might 
     //sometimes not necessarily have either cars or usedCars

    }

}
*/

// You can just map the arrays and spread them into a new array:
// If you have to deal with certain properties not being there,
// you can use optional chaining, the ? and ?? [] pieces
const names = [
  ...fakeData?.cars?.map(({name}) => name) ?? [],
  ...fakeData?.usedCars?.map(({name}) => name) ?? []
];

console.log(names); // ["CALI", "TEXAS", "NY", "FL"]

Upvotes: 0

Related Questions