• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

Looping through an array with objects

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have an object that has several key/values and it’s being passed as an argument to my function’s parameter as an array.

I need that function to iterate through said array that has objects in its indexes and it also needs to check if any of the array’s indexes key/values pairs have a string.

If there are strings, have those key/value pairs with strings be inside a new array that will be used to return it to the function.

The function’s returned value will be tested in a comparison in a TDD were an actual value is compared with an expected value.

In this case an array with an object with string values.


//TDD TEST
function test(actual, expected) {
   if (JSON.stringify(actual) === JSON.stringify(expected)) {
     console.log("Yay! Test PASSED.");
   } else {
     console.error("Test FAILED. Keep trying!");
     console.log("    actual: ", actual);
     console.log("  expected: ", expected);
     console.trace();
   }
 }

//The objects

const obj1 = { a: "A" };
const obj2 = { a: "A", b: 2 };
const obj3 = { a: "A", b: 2, c: "C", d: true };
const obj4 = { a: "A", c: "C" };

//My solution up to now
function filterArrayForStrings(arrayOfObjects){
 let newArrayWithObjects = [];
 for(const key in arrayOfObjects){
   if(typeof arrayOfObjects[key] === 'string'){
     newArrayWithObjects.push(arrayOfObjects[key]);
   }
   
 }
 return newArrayWithObjects;
}


test(filterArrayForStrings([obj1]), [obj1]);
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!