简体   繁体   English

将动态值与object中的object.keys匹配

[英]match dynamic value with object.keys in object

if It's array I can do like so myArr[0] to get the first value, but what if it's an object? 如果是数组,我可以这样做,使myArr [0]获得第一个值,但是如果它是一个对象呢? 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. ['a', 'b'].map(o => //match object return true)我期望得到[true, true]因为['a','b']的数组与宾语。

Use map and in : inin使用map

 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: 或者如果该属性可能存在于原型链中,并且您不想包括继承的属性,请改用Object.keys

 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. Object.hasOwnProperty效果很好。

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. 根据需要使用const或var。

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; //找到= true,如果它与键if(found){values [tag] = values [tag] +1; // this increase the count of the speific object key. //这会增加特定对象键的数量。 }else{ values[tag] =1; } else {values [tag] = 1; // this sets the value to 1 only once for all keys which are not present in the JS Object } } // //将所有JS对象中不存在的键的值一次设置为1}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM