Ryan
Ryan

Reputation: 1

Looping through multiple arrays in an Object to create multiple Objects in a new Array?

In my application, $scope.results = [{},{},{},{}.....].(Is an Array containing multiple objects)

Sample Output from one of the Objects:

0:
brand: "Confidential"
group_id: "CRCLEBESP"
id: "d703187ac59976b066c9b7ea01416bca"
msrp: "0"
name: "Clear Beyond Speaker Cable"
price: "5510"
product_type_unigram: "cable"
sku: "CRCLEBESP"
ss_msrp: (12) ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]
ss_msrp_max: "0"
ss_msrp_min: "0"
ss_name_sizes: "Cardas Clear Beyond Speaker Cable"
ss_price: (12) ["6840", "5510", "9500", "8170", "8170", "12160", "10830", "14820", "13490", "17480", "16150", "18810"]
ss_price_max: "18810"
ss_price_min: "5510"
stock_id: "171038"
sub_sku: (12) ["1.5PSPSP", "1PSPSP", "2.5PSPSP", "2PBNBN", "2PSPSP", "3.5PSPSP", "3PSPSP", "4.5PSPSP", "4PSPSP", "5.5PSPSP", "5PSPSP", "6PSPSP"]
uid: "171038"
__proto__: Object

Those objects contain 3 arrays each that I need to pull values from called "ss_msrp , ss_price, and sub_sku". Each array in each object is the same length. For example, Object 0 has 3 arrays, each array is 12 indexes long. Object 1 has 3 arrays, each array is 6 indexes long. Object 3 has 3 arrays, each array is 8 indexes long etc.

I need to pull the [n]th item from each array and place it into a new object. Each object will have 3 key-value pairs. For example:

ss_msrp = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]
ss_price = ["6840", "5510", "9500", "8170", "8170", "12160", "10830", "14820", "13490", "17480", "16150", "18810"]
sub_sku = ["1.5PSPSP", "1PSPSP", "2.5PSPSP", "2PBNBN", "2PSPSP", "3.5PSPSP", "3PSPSP", "4.5PSPSP", "4PSPSP", "5.5PSPSP", "5PSPSP", "6PSPSP"]

object1 = { msrp: "0", price: "6840", sku: "1.5PSPSP" }
object2 = { msrp: "0", price: "5510", sku: "1PSPSP" }
object3 = { msrp: "0", price: "9500", sku: "2.5PSPSP" }
object4 = { msrp: "0", price: "8170", sku: "2PBNBN" }

My code right now looks like this:

let objects = []

for (let i=0; i < $scope.results[0].sub_sku.length; i++){   
    objects.push({
        sku: $scope.results[0].sub_sku[i],
        msrp: $scope.results[0].ss_msrp[i],
        price: $scope.results[0].ss_price[i]
        })
    }

This of course will only return the desired results for the first object. I have tried nesting this inside another for loop like this:

for (let x=0; x < $scope.results.length; x++){
                for (let i=0; i < $scope.results[x].sub_sku.length; i++){   
                    objects.push({
                        sku: $scope.results[x].sub_sku[i],
                        msrp: $scope.results[x].ss_msrp[i],
                        price: $scope.results[x].ss_price[i]
                    })
                }
            }

but I am getting the following error: Cannot read property 'length' of undefined

Anyone have any ideas? Thank you in advance.

Upvotes: 0

Views: 99

Answers (3)

Senthur Athiban
Senthur Athiban

Reputation: 146

Suppose if your input has 2 objects in an array

Example:

let examples=[
    {
    brand: "Confidential",
    group_id: "CRCLEBESP",
    id: "d703187ac59976b066csds9b7ea01416bca",
    msrp: "0",
    name: "Clear Beyond Speaker Cable",
    price: "5510",
    product_type_unigram: "cable",
    sku: "CRCLEBESP",
    ss_msrp:["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"],
    ss_msrp_max: "0",
    ss_msrp_min: "0",
    ss_name_sizes: "Cardas Clear Beyond Speaker Cable",
    ss_price:["6840", "5510", "9500", "8170", "8170", "12160", "10830", "14820", "13490", "17480", "16150", "18810"],
    ss_price_max: "18810",
    ss_price_min: "5510",
    stock_id: "171038",
    sub_sku:["1.5PSPSP", "1PSPSP", "2.5PSPSP", "2PBNBN", "2PSPSP", "3.5PSPSP", "3PSPSP", "4.5PSPSP", "4PSPSP", "5.5PSPSP", "5PSPSP", "6PSPSP"],
    uid: "171038",
},
{
    brand: "Confidential",
    group_id: "CRCLEBESP",
    id: "d703187ac59976b066c9b7ea01416bca",
    msrp: "0",
    name: "Clear Beyond Speaker Cable",
    price: "5510",
    product_type_unigram: "cable",
    sku: "CRCLEBESP",
    ss_msrp:["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"],
    ss_msrp_max: "0",
    ss_msrp_min: "0",
    ss_name_sizes: "Cardas Clear Beyond Speaker Cable",
    ss_price:["6840", "5510", "9500", "8170", "8170", "12160", "10830", "14820", "13490", "17480", "16150", "18810"],
    ss_price_max: "18810",
    ss_price_min: "5510",
    stock_id: "171038",
    sub_sku:["1.5PSPSP", "1PSPSP", "2.5PSPSP", "2PBNBN", "2PSPSP", "3.5PSPSP", "3PSPSP", "4.5PSPSP", "4PSPSP", "5.5PSPSP", "5PSPSP", "6PSPSP"],
    uid: "171038",
}]

You can handle 2 cases,

  1. If your array of objects contains 2 same Products and you need 2 repeated objects with price,sku and msrp then this is one of the solution.
let result = examples.map(row=>{
   return row.ss_msrp.map((e,i)=>{
        return {
            msrp:row.ss_msrp[i],
            sku:row.sub_sku[i],
            price:row.ss_price[i]
        };
   });
});

Output:
// console.log(result);
// (2) [Array(12), Array(12)]
// It will print an array which contains array of objects of each product
// eg: [[{msrp: "0", sku: "5PSPSP", price: "16150"},....(12 entries)],[{msrp: "0", sku: "5PSPSP", price: "16150"},....(12 entries)]]

2.If you Don't want duplicate Products also a reference to the product id if id's are unique then you can also do this.

let result = {};
examples.map(row=>{
    result[row.id]= row.ss_msrp.map((e,i)=>{
        return {
        msrp:row.ss_msrp[i],
        sku:row.sub_sku[i],
        price:row.ss_price[i]
        };
    });
});

Output:
//console.log(result);
// {d703187ac59976b066c9b7ea01416bca: (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]}

Upvotes: 1

Cat
Cat

Reputation: 4246

Is this the output you're trying to get?

// Defines the source array (equivalent to `$scope.result`)
const threeArrsPerObj = [
  {
    ss_msrp:  ["0",          "0",          "0",          "0"],
    ss_price: ["6840",       "5510",       "9500",       "8170"],
    sub_sku:  ["1.5PSPSP",   "1PSPSP",     "2.5PSPSP",   "2PBNBN"]
  },
  {
    ss_msrp:  ["0",           "0",          "0",          "0"],
    ss_price: ["8170",        "12160",      "10830",      "14820"],
    sub_sku:  ["2PSPSP",      "3.5PSPSP",   "3PSPSP",     "4.5PSPSP"]
  },
  {
    ss_msrp: ["0",            "0",          "0",          "0"],
    ss_price: ["13490",       "17480",      "16150",      "18810"],
    sub_sku: ["4PSPSP",       "5.5PSPSP",   "5PSPSP",     "6PSPSP"]
  }
];

// Defines the destination array (equivalent to `objects`)
const multipleObjsPerArr = [];

// Loops through the source array and processes each object
threeArrsPerObj.forEach(obj => {

  // Defines arrays to use for the object currently being processed
  const
    msrpArr = obj.ss_msrp,
    priceArr = obj.ss_price,
    skuArr = obj.sub_sku,

    // The result Array will be the new version of the source object
    // **If you want to make a result Object instead, use `resultObj = {};`
    resultArr = [];
    //resultObj = {};

  // Loops through msrp array (Could use any of the 3 arrays b/c their lengths are the same)
  msrpArr.forEach( (_,index) => { // `_` stores the element (which we don't use)

    // Defines a new object to add to the result Array for the object being processed
    //   and stores the Nth element from each relevant array in a property of the new object
    const newObj = {
      msrp: msrpArr[index],
      price: priceArr[index],
      sku: skuArr[index]
    };

    // Adds the index-specific object to the result Array for the curreny source object
    //  **If you're making a result Object instead, use `resultObj["prop"+index] = newObj;`
    resultArr.push(newObj);
    //resultObj["prop"+index] = newObj;
  });

  // Pushes the Array version of the source object to the destination array
  //  **If you're making a result Object instead, push the resutObj
  multipleObjsPerArr.push(resultArr);
  //multipleObjsPerArr.push(resultObj);  
});

// Logs the contents of the destination array, one element at a time
multipleObjsPerArr.forEach( (subArray, index) => {
  console.log("\n Object including arrays (#" + (index + 1) + ") converted to array of objects:");
  console.log(subArray);
});

Upvotes: 0

Fawaz Ibrahim
Fawaz Ibrahim

Reputation: 181

I think that you should just correct the loop condition you wrote, the sub_sku is the array that you must get the length of, and not the sub_sku[i], your code should be like this:

let objects = []

for (let i=0; i < $scope.results[0].sub_sku.length; i++){    
    objects.push({
        sku: $scope.results[0].sub_sku[i],
        msrp: $scope.results[0].ss_msrp[i],
        price: $scope.results[0].ss_price[i]
        })
}

And if you want to apply the logic on all the Results , you'll have two use two for loops like this:

for (let j=0; j < $scope.results.length; j++){
    for (let i=0; i < $scope.results[j].sub_sku.length; i++){    
    objects.push({
        sku: $scope.results[j].sub_sku[i],
        msrp: $scope.results[j].ss_msrp[i],
        price: $scope.results[j].ss_price[i]
        })
    }
}

Upvotes: 0

Related Questions