Hello,
I am working on a coding challenge where I take this object:
var currentInventory = [
{
name: 'Brunello Cucinelli',
shoes: [
{name: 'tasselled black low-top lace-up', price: 1000},
{name: 'tasselled green low-top lace-up', price: 1100},
{name: 'plain beige suede moccasin', price: 950},
{name: 'plain olive suede moccasin', price: 1050}
]
},
{
name: 'Gucci',
shoes: [
{name: 'red leather laced sneakers', price: 800},
{name: 'black leather laced sneakers', price: 900}
]
}
];
And form a series of strings, like this:
//...console output:
Brunello Cucinelli, tasselled black low-top lace-up, 1000
Brunello Cucinelli, tasselled green low-top lace-up, 1100
// and so on...
I was able to get pretty far with this current code:
function renderInventory(inventory) {
//main function
}
//helper function to loop through individual
//Brunello and Gucci objects
function extractString(obj) {
let myArr = [];
for (let prop in obj) {
if (typeof obj[prop] === "number") { //if the property value
obj[prop] += "\n"; //is a number or string,
} //then add it to myArr
//to join(), later
if (typeof obj[prop] == "string" || typeof obj[prop] == "number") {
myArr.push(obj[prop]);
}
if (Array.isArray(obj[prop])) { //if the prop is an array,
for (let item of obj[prop]) { //then loop through and
myArr.push(extractString(item)) //recursively call the
} //function to unpack
} //its objects, further
}
return myArr
}
The resulting myArr
looks like this when I console.log()
:
[ 'Brunello Cucinelli',
[ 'tasselled black low-top lace-up', '1000\n' ],
[ 'tasselled green low-top lace-up', '1100\n' ],
[ 'plain beige suede moccasin', '950\n' ],
[ 'plain olive suede moccasin', '1050\n' ] ]
Here’s the problem. I basically want to unshift()
the Brunello Cucinelli
string to each of the items in the array and then join()
them, but it’s not working. When I console.log()
the individual elements, myArr[0]
comes up as Brunello Cucinelli
, but myArr[1]
comes up as 1000
, and the rest come up as undefined
. Furthermore, all of the subArrays typeof
comes up as a string
. I can’t loop through the subarrays, much less .join()
them because JS is not recognizing that they exist.
Can someone please advise? Thank you.