1

I am trying to extract and push the elements from an array of object to an empty object. Here is the example of the arrays.

const products = ["cars", "phones", "laptops"];

const productArrayOfObj = [
  {
    cars: ["Ford", "Chevy", "Honda", "Toyota"],
  },
  {
    phones: ["iPhone", "Samsung", "Nokia", "Sony"],
  },
  {
    laptops: ["Mac", "Dell", "HP", "Acer"],
  },
];

const mappedProducts= products.map((_,i) => productArrayOfObj[i]);

From mappedProducts returns this structure, even though I am not sure if this is the correct way of mapping this.

 [ { cars: [ 'Ford', 'Chevy', 'Honda', 'Toyota' ] }, 
  { phones: [ 'iPhone', 'Samsung', 'Nokia', 'Sony' ] }, 
  { laptops: [ 'Mac', 'Dell', 'HP', 'Acer' ] } ]

My desired array would look like this

[ 'Ford', 'Chevy', 'Honda', 'Toyota','iPhone', 'Samsung', 'Nokia',
  'Sony','Mac', 'Dell', 'HP', 'Acer' ]

The way I'm trying to implement it, returns wrong result.

const arrayToPush = []
const getArrayEl = mappedProducts && mappedProducts.map(item => { 
for(let key in item){
    arrayToPush.push(item[key])
}
  return arrayToPush
})

Any help will be appreciated

const names = ["cars", "phones", "laptops"];

const nameArrayOfObj = [
  {
    cars: ["Ford", "Chevy", "Honda", "Toyota"],
  },
  {
    phones: ["iPhone", "Samsung", "Nokia", "Sony"],
  },
  {
    laptops: ["Mac", "Dell", "HP", "Acer"],
  },
];

const mappedProducts = names && nameArrayOfObj && names.map((_,i) => nameArrayOfObj[i]);

console.log("mappedProducts", mappedProducts);
const arrayToPush = []
const getArrayEl = mappedProducts && mappedProducts.map(item => { 
for(let key in item){
    arrayToPush.push(item[key])
}
  return arrayToPush
})
console.log("getArrayEl", getArrayEl);

2
  • 1
    So you want to add only the arrays of wich the key exist in names? Commented Apr 5, 2022 at 11:26
  • @0stone0 yes, that is my question Commented Apr 5, 2022 at 11:31

3 Answers 3

3

You could use two .flatMap() calls, to loop through your array of product objects, and then an inner one to loop through your names from the products array. For each name, you can take the associated array from the object at that name:

const products = ["cars", "phones", "laptops"];
const productArrayOfObj = [ { cars: ["Ford", "Chevy", "Honda", "Toyota"], }, { phones: ["iPhone", "Samsung", "Nokia", "Sony"], }, { laptops: ["Mac", "Dell", "HP", "Acer"], }, ];

const res = productArrayOfObj.flatMap(obj => products.flatMap(
  name => obj[name] ?? []
));
console.log(res);

If your objects can only contain one key-array pair, then you can change your inner .flatMap() to a .find() to find the key being used in the object:

const products = ["cars", "phones", "laptops"];
const productArrayOfObj = [ { cars: ["Ford", "Chevy", "Honda", "Toyota"], }, { phones: ["iPhone", "Samsung", "Nokia", "Sony"], }, { laptops: ["Mac", "Dell", "HP", "Acer"], }, ];

const res = productArrayOfObj.flatMap(obj => {
  const key = products.find(name => obj.hasOwnProperty(name));
  return key ? obj[key] : [];
});
console.log(res);

Sign up to request clarification or add additional context in comments.

3 Comments

This should be the accepted answer as it actually checks the key exists in the products list.
@Pellay I had also included the same logic in my answer, then why does this comment states this SHOULD be the accepted answer?
@Nitheesh. Your first function is flawed; as stated in the comments from the OP's post, he wants a function that can return a flattened list of results based on the values of the products array. Your first function fails at this. Your second function returns an array of arrays not matching the OP's request. Nick's answer here works in both cases.
2

Is this your solution? Using the keys from products and flatMap()

const products = ["cars", "phones", "laptops"];

const productArrayOfObj = [
  {
    cars: ["Ford", "Chevy", "Honda", "Toyota"],
  },
  {
    phones: ["iPhone", "Samsung", "Nokia", "Sony"],
  },
  {
    laptops: ["Mac", "Dell", "HP", "Acer"],
  },
];

const mappedProducts= products.flatMap((_,i) => productArrayOfObj[i][_]);
console.log(mappedProducts)

Comments

2

Array.flatMap implementation.

Logic

  • Loop through names array with Array.flatMap.
  • Access each keys from nameArrayOfObj.

This implementation makes use of an asumprion that both arrays are in same order.

Working Fiddle

const names = ["cars", "phones", "laptops"];
const nameArrayOfObj = [
  { cars: ["Ford", "Chevy", "Honda", "Toyota"] },
  { phones: ["iPhone", "Samsung", "Nokia", "Sony"] },
  { laptops: ["Mac", "Dell", "HP", "Acer"] },
];
const mappedProducts = names.flatMap((name, i) => nameArrayOfObj[i][name] ? nameArrayOfObj[i][name] : []);
console.log(mappedProducts);

If you cannot ensure the arrays ae in same order, you can make use of this logic.

  • Loop through names Array.
  • Find an item from nameArrayOfObj array with the key in names Array.

Working Fiddle

const names = ["cars", "phones", "laptops"];
const nameArrayOfObj = [
  { cars: ["Ford", "Chevy", "Honda", "Toyota"] },
  { phones: ["iPhone", "Samsung", "Nokia", "Sony"] },
  { laptops: ["Mac", "Dell", "HP", "Acer"] },
];
const mappedProducts = names.flatMap((name, i) => {
  const matchingNode = nameArrayOfObj.find(item => item.hasOwnProperty(name));
  return matchingNode ? matchingNode[name] : [];
});
console.log(mappedProducts);

5 Comments

The problem with your initial answer is it relies entirely on the names array being exactly the same as the object keys in the namesArrayOfObj, which totally negates having the names array in the first place.
@Pellay I already have stated that my first solution expects the order of both array should be the same. I have also added a generic solution where the order of both arrays are not dependent.
I didn't dispute that? I simply pointed out it's a pointless function. Why does it even matter what is in the first array. Since your function completely fails if there is any variation in the initial array it is a completely pointless method to extract data from the second array. if I ask for just ["cars", "laptops"], I only get Cars. ["cars", "laptops", "phones"] I only get cars again. unless it's 1 for 1 it literally has no benefit from just flattening the second array.
@Pellay I dont want to argue. I have added my point in the answer. If any changes needed the user himself can change the function to his desired output.
no drama mate. I wasn't trying to attacking you, just critiquing the code. Take care mate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.