admin管理员组文章数量:1356900
if It's array I can do like so myArr[0] to get the first value, but what if it's an object? says my object is like this
{a: 'some value', b: 'another thing'}
How can I match the first object?
['a', 'b'].map(o => //match object return true)
I expect to get [true, true]
because the array of ['a','b']
match the key value of the object.
if It's array I can do like so myArr[0] to get the first value, but what if it's an object? says my object is like this
{a: 'some value', b: 'another thing'}
How can I match the first object?
['a', 'b'].map(o => //match object return true)
I expect to get [true, true]
because the array of ['a','b']
match the key value of the object.
- Maybe I'm misunderstanding your question, but there is not first value in objects — properties are unordered. – Mark Commented Jul 2, 2018 at 2:06
3 Answers
Reset to default 6Use map
and in
:
const obj = {a: 'some value', b: 'another thing'};
console.log(['a', 'foo', 'b'].map(key => key in obj));
or if the property might exist in the prototype chain and you don't want to include inherited properties, use Object.keys
instead:
const obj = {
a: 'some value',
b: 'another thing'
};
const keys = Object.keys(obj);
console.log(['a', 'foo', 'b'].map(key => keys.includes(key)));
let obj = {
a: 'some value',
b: 'another thing'
};
console.log(['a', 'b'].map(key => obj.hasOwnProperty(key)));
Object.hasOwnProperty works well.
let values = new Object(); // bad practice
let values = {}; // this is Good Practice "JS Object"
let tags= []; // this is Good Practice "JS Array"
use const or var based on your requirements.
Lets imagine tags is an array where you get the dynamic values based on the loops through.. so it is set dynamically and you will store these values and its occurrences in the values object-
for(let tag of tags){ // tags here is a dynamic array imagine
let found = Object.keys(values).find((element) => {
return element === tag;
});
// found = true, when it matches the key if(found){ values[tag] = values[tag] + 1; // this increase the count of the speific object key. }else{ values[tag] =1; // this sets the value to 1 only once for all keys which are not present in the JS Object } }
本文标签: javascriptmatch dynamic value with objectkeys in objectStack Overflow
版权声明:本文标题:javascript - match dynamic value with object.keys in object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743954898a2567955.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论