javascript function to search for object property and return value
I have a string:
const phrase = "there is a blue bird in the forest";
and an object:
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
I want to write a Javascript function that checks if the string contains any of the property of the color object and, if so, return the value for the matched property, so in the example above, it will return 20.
I'm using Lodash and I can't figure out how to write this function (_.some, _.find?)
javascript lodash
add a comment |
I have a string:
const phrase = "there is a blue bird in the forest";
and an object:
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
I want to write a Javascript function that checks if the string contains any of the property of the color object and, if so, return the value for the matched property, so in the example above, it will return 20.
I'm using Lodash and I can't figure out how to write this function (_.some, _.find?)
javascript lodash
Welcome to Stack Overflow :) Could you provide what you tried already?
– sp00m
Nov 23 '18 at 11:46
add a comment |
I have a string:
const phrase = "there is a blue bird in the forest";
and an object:
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
I want to write a Javascript function that checks if the string contains any of the property of the color object and, if so, return the value for the matched property, so in the example above, it will return 20.
I'm using Lodash and I can't figure out how to write this function (_.some, _.find?)
javascript lodash
I have a string:
const phrase = "there is a blue bird in the forest";
and an object:
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
I want to write a Javascript function that checks if the string contains any of the property of the color object and, if so, return the value for the matched property, so in the example above, it will return 20.
I'm using Lodash and I can't figure out how to write this function (_.some, _.find?)
javascript lodash
javascript lodash
edited Nov 23 '18 at 12:21
Pranesh Janarthanan
489616
489616
asked Nov 23 '18 at 11:44
Anthony BrebionAnthony Brebion
81
81
Welcome to Stack Overflow :) Could you provide what you tried already?
– sp00m
Nov 23 '18 at 11:46
add a comment |
Welcome to Stack Overflow :) Could you provide what you tried already?
– sp00m
Nov 23 '18 at 11:46
Welcome to Stack Overflow :) Could you provide what you tried already?
– sp00m
Nov 23 '18 at 11:46
Welcome to Stack Overflow :) Could you provide what you tried already?
– sp00m
Nov 23 '18 at 11:46
add a comment |
8 Answers
8
active
oldest
votes
If you need to get the total value of all colors in a string, you can use Array.reduce() (or lodash's _.reduce()). Change the phrase to lower case, split it by spaces, reduce, and take sum the value of the color (or 0 for other words):
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
const getColorsValue = (p) =>
p.toLowerCase()
.split(/s+/)
.reduce((s, w) => s + (color[w] || 0), 0);
console.log(getColorsValue('there is a blue bird in the forest')); // 20
console.log(getColorsValue('there is a blue bird in the red forest')); // 30add a comment |
This will be useful for you, check this out or find code below: https://dustinpfister.github.io/2017/09/14/lodash-find/
var db_array = [
{
name : 'Dave',
sex : 'male',
age : 34
},
{
name: 'Jake',
sex : 'male',
age : 22
},
{
name :'Jane',
sex : 'female',
age : 27
}
],
// find dave
q = _.find(db_array, {name:'Dave'});
console.log(q); // {name:'Dave',sex:male,age:34}
add a comment |
Try Underscore.js Library. _.where(list, properties)
add a comment |
This should help you!
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
const phraseValues = phrase.split(' ');
const colorValues = Object.keys(color)
const isKeyPresent = !!_.intersection(phraseValues , colorValues).length
add a comment |
We can achieve this utilising JavaScript's Object.keys() and .find()
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];
console.log(result); // 20add a comment |
Using js:
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
let key = Object.keys(color).find(color => phrase.includes(color));
if(key) console.log(color[key]);add a comment |
You can use Array.flatMap and Array.split as well
const phrase = "there is a blue bird in the forest";
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
let res = phrase.split(' ').flatMap(d => color[d] || )
console.log(res[0] || 'No color is present')add a comment |
You could also use the String.replace handler inside an Array.reduce on the colors to go though each and calculate the final sum.
const data = "blue and red bird with blue feathers"
const color = { 'blue': 20, 'red': 10, 'yellow': 5 }
const result = Object.keys(color).reduce((r, k) =>
(data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)
console.log(result) // 50 since it has 2 "blue" and 1 "red"add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53446083%2fjavascript-function-to-search-for-object-property-and-return-value%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
8 Answers
8
active
oldest
votes
8 Answers
8
active
oldest
votes
active
oldest
votes
active
oldest
votes
If you need to get the total value of all colors in a string, you can use Array.reduce() (or lodash's _.reduce()). Change the phrase to lower case, split it by spaces, reduce, and take sum the value of the color (or 0 for other words):
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
const getColorsValue = (p) =>
p.toLowerCase()
.split(/s+/)
.reduce((s, w) => s + (color[w] || 0), 0);
console.log(getColorsValue('there is a blue bird in the forest')); // 20
console.log(getColorsValue('there is a blue bird in the red forest')); // 30add a comment |
If you need to get the total value of all colors in a string, you can use Array.reduce() (or lodash's _.reduce()). Change the phrase to lower case, split it by spaces, reduce, and take sum the value of the color (or 0 for other words):
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
const getColorsValue = (p) =>
p.toLowerCase()
.split(/s+/)
.reduce((s, w) => s + (color[w] || 0), 0);
console.log(getColorsValue('there is a blue bird in the forest')); // 20
console.log(getColorsValue('there is a blue bird in the red forest')); // 30add a comment |
If you need to get the total value of all colors in a string, you can use Array.reduce() (or lodash's _.reduce()). Change the phrase to lower case, split it by spaces, reduce, and take sum the value of the color (or 0 for other words):
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
const getColorsValue = (p) =>
p.toLowerCase()
.split(/s+/)
.reduce((s, w) => s + (color[w] || 0), 0);
console.log(getColorsValue('there is a blue bird in the forest')); // 20
console.log(getColorsValue('there is a blue bird in the red forest')); // 30If you need to get the total value of all colors in a string, you can use Array.reduce() (or lodash's _.reduce()). Change the phrase to lower case, split it by spaces, reduce, and take sum the value of the color (or 0 for other words):
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
const getColorsValue = (p) =>
p.toLowerCase()
.split(/s+/)
.reduce((s, w) => s + (color[w] || 0), 0);
console.log(getColorsValue('there is a blue bird in the forest')); // 20
console.log(getColorsValue('there is a blue bird in the red forest')); // 30const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
const getColorsValue = (p) =>
p.toLowerCase()
.split(/s+/)
.reduce((s, w) => s + (color[w] || 0), 0);
console.log(getColorsValue('there is a blue bird in the forest')); // 20
console.log(getColorsValue('there is a blue bird in the red forest')); // 30const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
const getColorsValue = (p) =>
p.toLowerCase()
.split(/s+/)
.reduce((s, w) => s + (color[w] || 0), 0);
console.log(getColorsValue('there is a blue bird in the forest')); // 20
console.log(getColorsValue('there is a blue bird in the red forest')); // 30answered Nov 23 '18 at 12:35
Ori DroriOri Drori
77.3k138292
77.3k138292
add a comment |
add a comment |
This will be useful for you, check this out or find code below: https://dustinpfister.github.io/2017/09/14/lodash-find/
var db_array = [
{
name : 'Dave',
sex : 'male',
age : 34
},
{
name: 'Jake',
sex : 'male',
age : 22
},
{
name :'Jane',
sex : 'female',
age : 27
}
],
// find dave
q = _.find(db_array, {name:'Dave'});
console.log(q); // {name:'Dave',sex:male,age:34}
add a comment |
This will be useful for you, check this out or find code below: https://dustinpfister.github.io/2017/09/14/lodash-find/
var db_array = [
{
name : 'Dave',
sex : 'male',
age : 34
},
{
name: 'Jake',
sex : 'male',
age : 22
},
{
name :'Jane',
sex : 'female',
age : 27
}
],
// find dave
q = _.find(db_array, {name:'Dave'});
console.log(q); // {name:'Dave',sex:male,age:34}
add a comment |
This will be useful for you, check this out or find code below: https://dustinpfister.github.io/2017/09/14/lodash-find/
var db_array = [
{
name : 'Dave',
sex : 'male',
age : 34
},
{
name: 'Jake',
sex : 'male',
age : 22
},
{
name :'Jane',
sex : 'female',
age : 27
}
],
// find dave
q = _.find(db_array, {name:'Dave'});
console.log(q); // {name:'Dave',sex:male,age:34}
This will be useful for you, check this out or find code below: https://dustinpfister.github.io/2017/09/14/lodash-find/
var db_array = [
{
name : 'Dave',
sex : 'male',
age : 34
},
{
name: 'Jake',
sex : 'male',
age : 22
},
{
name :'Jane',
sex : 'female',
age : 27
}
],
// find dave
q = _.find(db_array, {name:'Dave'});
console.log(q); // {name:'Dave',sex:male,age:34}
answered Nov 23 '18 at 11:52
shadowman_93shadowman_93
15712
15712
add a comment |
add a comment |
Try Underscore.js Library. _.where(list, properties)
add a comment |
Try Underscore.js Library. _.where(list, properties)
add a comment |
Try Underscore.js Library. _.where(list, properties)
Try Underscore.js Library. _.where(list, properties)
answered Nov 23 '18 at 11:55
Pranesh JanarthananPranesh Janarthanan
489616
489616
add a comment |
add a comment |
This should help you!
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
const phraseValues = phrase.split(' ');
const colorValues = Object.keys(color)
const isKeyPresent = !!_.intersection(phraseValues , colorValues).length
add a comment |
This should help you!
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
const phraseValues = phrase.split(' ');
const colorValues = Object.keys(color)
const isKeyPresent = !!_.intersection(phraseValues , colorValues).length
add a comment |
This should help you!
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
const phraseValues = phrase.split(' ');
const colorValues = Object.keys(color)
const isKeyPresent = !!_.intersection(phraseValues , colorValues).length
This should help you!
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
const phraseValues = phrase.split(' ');
const colorValues = Object.keys(color)
const isKeyPresent = !!_.intersection(phraseValues , colorValues).length
answered Nov 23 '18 at 12:01
Diljohn5741Diljohn5741
38916
38916
add a comment |
add a comment |
We can achieve this utilising JavaScript's Object.keys() and .find()
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];
console.log(result); // 20add a comment |
We can achieve this utilising JavaScript's Object.keys() and .find()
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];
console.log(result); // 20add a comment |
We can achieve this utilising JavaScript's Object.keys() and .find()
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];
console.log(result); // 20We can achieve this utilising JavaScript's Object.keys() and .find()
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];
console.log(result); // 20const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];
console.log(result); // 20const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];
console.log(result); // 20edited Nov 23 '18 at 12:49
Nitish Narang
2,9401815
2,9401815
answered Nov 23 '18 at 11:53
Benjamin RussellBenjamin Russell
1296
1296
add a comment |
add a comment |
Using js:
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
let key = Object.keys(color).find(color => phrase.includes(color));
if(key) console.log(color[key]);add a comment |
Using js:
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
let key = Object.keys(color).find(color => phrase.includes(color));
if(key) console.log(color[key]);add a comment |
Using js:
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
let key = Object.keys(color).find(color => phrase.includes(color));
if(key) console.log(color[key]);Using js:
const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
let key = Object.keys(color).find(color => phrase.includes(color));
if(key) console.log(color[key]);const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
let key = Object.keys(color).find(color => phrase.includes(color));
if(key) console.log(color[key]);const phrase = "there is a blue bird in the forest";
const color = { 'blue': 20, 'red': 10, 'yellow': 5 };
let key = Object.keys(color).find(color => phrase.includes(color));
if(key) console.log(color[key]);edited Nov 23 '18 at 12:55
Nitish Narang
2,9401815
2,9401815
answered Nov 23 '18 at 11:52
Sagar JajoriyaSagar Jajoriya
1,8261310
1,8261310
add a comment |
add a comment |
You can use Array.flatMap and Array.split as well
const phrase = "there is a blue bird in the forest";
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
let res = phrase.split(' ').flatMap(d => color[d] || )
console.log(res[0] || 'No color is present')add a comment |
You can use Array.flatMap and Array.split as well
const phrase = "there is a blue bird in the forest";
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
let res = phrase.split(' ').flatMap(d => color[d] || )
console.log(res[0] || 'No color is present')add a comment |
You can use Array.flatMap and Array.split as well
const phrase = "there is a blue bird in the forest";
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
let res = phrase.split(' ').flatMap(d => color[d] || )
console.log(res[0] || 'No color is present')You can use Array.flatMap and Array.split as well
const phrase = "there is a blue bird in the forest";
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
let res = phrase.split(' ').flatMap(d => color[d] || )
console.log(res[0] || 'No color is present')const phrase = "there is a blue bird in the forest";
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
let res = phrase.split(' ').flatMap(d => color[d] || )
console.log(res[0] || 'No color is present')const phrase = "there is a blue bird in the forest";
const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
let res = phrase.split(' ').flatMap(d => color[d] || )
console.log(res[0] || 'No color is present')edited Nov 23 '18 at 17:01
answered Nov 23 '18 at 12:43
Nitish NarangNitish Narang
2,9401815
2,9401815
add a comment |
add a comment |
You could also use the String.replace handler inside an Array.reduce on the colors to go though each and calculate the final sum.
const data = "blue and red bird with blue feathers"
const color = { 'blue': 20, 'red': 10, 'yellow': 5 }
const result = Object.keys(color).reduce((r, k) =>
(data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)
console.log(result) // 50 since it has 2 "blue" and 1 "red"add a comment |
You could also use the String.replace handler inside an Array.reduce on the colors to go though each and calculate the final sum.
const data = "blue and red bird with blue feathers"
const color = { 'blue': 20, 'red': 10, 'yellow': 5 }
const result = Object.keys(color).reduce((r, k) =>
(data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)
console.log(result) // 50 since it has 2 "blue" and 1 "red"add a comment |
You could also use the String.replace handler inside an Array.reduce on the colors to go though each and calculate the final sum.
const data = "blue and red bird with blue feathers"
const color = { 'blue': 20, 'red': 10, 'yellow': 5 }
const result = Object.keys(color).reduce((r, k) =>
(data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)
console.log(result) // 50 since it has 2 "blue" and 1 "red"You could also use the String.replace handler inside an Array.reduce on the colors to go though each and calculate the final sum.
const data = "blue and red bird with blue feathers"
const color = { 'blue': 20, 'red': 10, 'yellow': 5 }
const result = Object.keys(color).reduce((r, k) =>
(data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)
console.log(result) // 50 since it has 2 "blue" and 1 "red"const data = "blue and red bird with blue feathers"
const color = { 'blue': 20, 'red': 10, 'yellow': 5 }
const result = Object.keys(color).reduce((r, k) =>
(data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)
console.log(result) // 50 since it has 2 "blue" and 1 "red"const data = "blue and red bird with blue feathers"
const color = { 'blue': 20, 'red': 10, 'yellow': 5 }
const result = Object.keys(color).reduce((r, k) =>
(data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)
console.log(result) // 50 since it has 2 "blue" and 1 "red"answered Nov 24 '18 at 6:26
AkrionAkrion
9,45511224
9,45511224
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53446083%2fjavascript-function-to-search-for-object-property-and-return-value%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Welcome to Stack Overflow :) Could you provide what you tried already?
– sp00m
Nov 23 '18 at 11:46