0

I have one array that I want to push a key/value from another array if the array contains a value that the other array have.

var array1 = [
  {
    "item":"carbon",
    "name_i18n": "UI_FUEL_1_NAME_L",
    "prefix":"resources",
  },
  {
    "item":"silver",
    "name_i18n": "UI_ASTEROID1_NAME_L",
    "prefix":"resources",
  },
]

I want to check if this array:

var array2 = [
{
  "recipe":"RECIPE_ASTEROID1__1",
  "ingredients":[
      {"item":"silver","qnt":"100"},
      {"item":"carbon","qnt":"100"},
  ]
},
{
  "recipe":"RECIPE_FUEL3__2",
  "ingredients":[
      {"item":"carbon","qnt":"50"},
      {"item":"carbon","qnt":"50"},
      {"item":"carbon","qnt":"50"},
  ]
},

Has the value of "item" in array1, if it has, I want to push the recipe key/value into the array1 but without duplicating it, because as you can see the second entry in array2 has 3 ingredients, with the same name, I don't want to put 3x key/value in array1.

Example output after check:

var array1 = [
  {
    "item":"carbon",
    "prefix":"resources",
    "recipe":"RECIPE_FUEL3__2",
  },
  {
    "item":"silver",
    "prefix":"resources",
    "recipe":"RECIPE_ASTEROID1__1",
  },
]

I already do a check if they have another property, using this code:

$.each( array1, function( key, value ) {
  if (name === value.name_i18n){
    name = value.item;
  }
});

Which I use to push the value of name into the array2, but it's one value only and not 3 like the example above.

RogerHN
  • 584
  • 1
  • 11
  • 31
  • 1
    Could you make working snippet demonstrating your problem? Could you also clarify why carbon should have "RECIPE_FUEL3__2" if it's in both recipes? I don't see `name_i18n` property in your arrays and I can't see what value has variable `name` – barbsan Aug 09 '18 at 12:36
  • Hi barbsan, I want add the recipe "RECIPE_FUEL3__2" to carbon because it uses carbon in ingredients.item. The function where I use name_i18n is just an example that I know how to check one value, but I don't know how to check all the values inside ingredients and not duplicate the recipe. I use that in another complex function where I use a parsed xml to generate the array with the recipes you can see it working here: https://codepen.io/RogerHN/pen/JBerjv – RogerHN Aug 09 '18 at 12:55
  • I meant, could you create [mcve](https://stackoverflow.com/help/mcve)? Snippet with > 7k lines is not much helpful, and really doesn't show how do you add ingredients from array1 to array2. Consider using [dictionary](https://stackoverflow.com/a/1208272/7404943) or [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instead of those endless `if`'s in `swap_recipe` and `swap_item` functions – barbsan Aug 10 '18 at 06:49

0 Answers0