1

I have an array of objects that look something like this;

[
{Number: 5002000, Origin: 123456, Count: 128},
{Number: 5002300, Origin: 900231, Count: 52},
{Number: 5002022, Origin: 534323, Count: 269}
]

Now I'm trying to multiply the "Count" value with a value from a designated price pool.

Which looks something like this;

[
{Prefix: 50023, Price: 20},    
{Prefix: 50020, Price: 10},
{Prefix: 5002, Price: 60},
]

Currently there's an horrendous for loop with if-statements.

for (var key in sData) {
  if (sData[key].Origin.startsWith('50023')) {
    sData[key].sum = (sData[key].Count * 20);
  }
  else if (sData[key].Origin.startsWith('50020')) {
    sData[key].sum = (sData[key].Count * 10);
  }
  // continues...
}

startsWith is a function that simply checks if the value starts with the (value).

Is there already a function in JS to map two arrays of objects? (I'm also having issues with the logic since the "Prefix" value basically has to go from the top down as not to land on the default "5002"-prefix.)

1
  • but the prefix 5002 covers the rest of prefixes. What is the priority? Commented May 16, 2016 at 6:54

2 Answers 2

1

You should use nested loops in this situation. Also switch to Array.forEach method.

sData.forEach(function(item_, key) {

          prices.forEach(function(item) {

             if (sData[key].Origin.startsWith(item.Prefix)) {
                sData[key].sum = (sData[key].Count * item.Price);
             }

          });  

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

4 Comments

Right, that was simple, let me try!
As your manipulating the item in the sData array a map would be preferable over forEach
@ste2425 - map method creates a new array. But here the OP needs to modify the original.
@CharlieH I missed that fact my bad, however you could do sData = sData.map(x => {}). Map is meant for manipulating the arrays contents, forEach for iterating. But on the flip side sData = sData.map(x => {}) does look ugly.
1

Assuming that second array can be transformed into the hash:

var tiers = {
    50023: {Prefix: 50023, Price: 20},    
    50020: {Prefix: 50020, Price: 10},
    5002: {Prefix: 5002, Price: 60},
}

You may make it look like this:

for (var key in sData) {
    var key = String(sData[key])
    var keyIndex = key.slice(5)

    if (tiers.hasOwnProperty(keyIndex)) {
        var price = tiers[keyIndex].Price
        sData[key].sum = (sData[key].Count * price)
    } else {
        // Fallback solution
    }
}

Going further you may even think of some recursive solution for fallback.

Comments

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.