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
orvar
can be used as an expression. Which resolves into the value you assign.someVariable = "foobar"
will resolve into"foobar"
, soreturn 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
4 Answers
Reset to default 7No 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 valuestrue
andfalse
. - You don't need to use the word "function", you can use lambda format instead
var
is rarely used nowadays, uselet
orconst
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
andincludes
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
版权声明:本文标题:javascript - How to use .map to add a new property to an array of objects - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741272300a2369530.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论