admin管理员组

文章数量:1278793

trying to use underscore.map to iterate over array of objects and add a boolean property to each object based on if the object value passes a truth statement.

var desserts = [
  {
    name: 'Chocolate Cake',
    ingredients: ['cocoa', 'flour', 'sugar', 'eggs', 'milk', 'butter' ],
    type: 'cake'
  },
  {
    name: 'Snickerdoodles',
    ingredients: ['flour', 'milk', 'butter', 'eggs', 'sugar', 'cinnamon', 'cream of tartar'],
    type: 'cookie'
  }, 

etc..

Heres what I have -

var glutenFree = function (desserts) {
  return _.map(desserts, function(dessert) {
    if (dessert.ingredients.includes('flour')) {
      return dessert.glutenFree = 'false';
    } else {
      return dessert.glutenFree = 'true';
    }
  });
};

trying to use underscore.map to iterate over array of objects and add a boolean property to each object based on if the object value passes a truth statement.

var desserts = [
  {
    name: 'Chocolate Cake',
    ingredients: ['cocoa', 'flour', 'sugar', 'eggs', 'milk', 'butter' ],
    type: 'cake'
  },
  {
    name: 'Snickerdoodles',
    ingredients: ['flour', 'milk', 'butter', 'eggs', 'sugar', 'cinnamon', 'cream of tartar'],
    type: 'cookie'
  }, 

etc..

Heres what I have -

var glutenFree = function (desserts) {
  return _.map(desserts, function(dessert) {
    if (dessert.ingredients.includes('flour')) {
      return dessert.glutenFree = 'false';
    } else {
      return dessert.glutenFree = 'true';
    }
  });
};
Share Improve this question asked Oct 16, 2022 at 23:40 boshao13boshao13 451 silver badge5 bronze badges 2
  • What do you want to know? is there is an error in your code? – Joseph Commented Oct 16, 2022 at 23:44
  • @connexo Yes you can, an assignment without cont, let or var can be used as an expression. Which resolves into the value you assign. someVariable = "foobar" will resolve into "foobar", so return dessert.glutenFree = 'false' will return 'false'. Though the behaviour is not what OP wants, it is valid. – 3limin4t0r Commented Oct 17, 2022 at 0:02
Add a ment  | 

4 Answers 4

Reset to default 7

No library needed:

const desserts = [{
    name: 'Chocolate Cake',
    ingredients: ['cocoa', 'flour', 'sugar', 'eggs', 'milk', 'butter'],
    type: 'cake'
  },
  {
    name: 'Snickerdoodles',
    ingredients: ['flour', 'milk', 'butter', 'eggs', 'sugar', 'cinnamon', 'cream of tartar'],
    type: 'cookie'
  }
];

const dessertsExtended = desserts.map(dessert => ({ ...dessert,
  glutenfree: !dessert.ingredients.includes('flour')
}));

console.log(dessertsExtended);

You just need to set the properties. Then return the element in the map function, so it gets added to the array.

var glutenFree = function (desserts) {
  return _.map(desserts, function(dessert) {
    if (dessert.ingredients.includes('flour')) {
      dessert.glutenFree = 'false';
      return dessert;
    } else {
     dessert.glutenFree = 'true';
     return dessert;
    }
  });
};

Though I'd make some adjustments.

  • Instead of the string values 'true' and 'false', you can use the boolean values true and false.
  • You don't need to use the word "function", you can use lambda format instead
  • var is rarely used nowadays, use let or const instead.
  • If you only use the if-else statement to assign stuff, you can also use the ternary operator <condition> ? <statement> : <statement>
const glutenFree = (desserts) => {
  return _.map(desserts, (dessert) => {
    dessert.glutenFee = dessert.ingredients.includes('flour')
      ? false
      : true;
    return dessert;
  });
};

Of course, dessert.ingredients.includes('flour') itself is also a boolean value that is either true or false. So you could make the function even shorter by using the boolean value of this statement. If it includes flower, it is not gluten-free. So add a ! in front to negate the boolean:

const glutenFree = (desserts) => {
  return _.map(desserts, (dessert) => {
    dessert.glutenFee = !dessert.ingredients.includes('flour');
    return dessert;
  });
};

The map creates a new array with the value that you pass in the return statement. In your case, return dessert.glutenFree = 'false'; is considered just as false, and return dessert.glutenFree = 'true'; is considered as true. Resulting in a array with just ['false', 'false'].

To return the whole object, you need to modify it and then return the whole object, here's the refactored function:

var glutenFree = function (desserts) {
  return desserts.map(function(dessert) {
    if (dessert.ingredients.includes('flour')) {
      dessert.glutenFree = 'false'; // modifying the object
    } else {
      dessert.glutenFree = 'true'; // modifying the object
    }

    return dessert; // returning the whole object
  });
};

The answer by connexo is essentially correct; it does not modify the input array. Also, you should use actual booleans (true and false) instead of strings that look like booleans ('true' and 'false').

However, connexo's answer does not use Underscore, as originally asked. Using Underscore has a small cost (your application grows by 8 kB), but it also has some benefits:

  • Underscore runs everywhere. While functions like map and includes and other features such as spread syntax are nowadays part of the language, they are not universally available. Depending on where your application needs to run, this often means you will be using transpilation and polyfills, which tend to inflate the size of your application much more than Underscore.
  • Underscore has some additional tricks pared to the standardized functions, such as iteratee shorthands and being able to iterate over plain objects. These can e in handy elsewhere in your application.

For these two reasons, I actually tend to use Underscore wherever I can. By exploiting the library to the max, you get maximum bang-for-bucks for those modest 8 kB of library.

Below is an Underscore-ified version of connexo's solution.

const desserts = [{
    name: 'Chocolate Cake',
    ingredients: ['cocoa', 'flour', 'sugar', 'eggs', 'milk', 'butter'],
    type: 'cake'
  },
  {
    name: 'Snickerdoodles',
    ingredients: ['flour', 'milk', 'butter', 'eggs', 'sugar', 'cinnamon', 'cream of tartar'],
    type: 'cookie'
  }
];

const dessertsExtended = _.map(desserts, function(dessert) {
    return _.defaults({
        glutenfree: !_.contains(dessert.ingredients, 'flour')
    }, dessert);
});

console.log(dessertsExtended);
<script src="https://cdn.jsdelivr/npm/[email protected]/underscore-umd-min.js"></script>

本文标签: javascriptHow to use map to add a new property to an array of objectsStack Overflow