最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - match dynamic value with object.keys in object - Stack Overflow

programmeradmin4浏览0评论

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.

Share Improve this question asked Jul 2, 2018 at 2:02 user9728810user9728810 1
  • 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
Add a ment  | 

3 Answers 3

Reset to default 6

Use 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 } }

发布评论

评论列表(0)

  1. 暂无评论