简体   繁体   English

通过对象数组进行映射,甚至通过与其他对象相比没有一两个键的对象进行映射

[英]Map through array of objects even through objects that don't have one or two keys compared to other objects

Title. 标题。 I can have two or three types of objects, but i would like to make reliable function to cover all other cases if any new keys/properties will be added to future objects. 我可以有两种或三种类型的对象,但是如果要向将来的对象添加任何新的键/属性,我想提供可靠的功能来涵盖所有其他情况。

Whenever i'm mapping through objects with the same properties ( obj1 , obj4 ) everything is K. The problem is when i want to make a function to map through all objects in arr with keys that may or may not be in particular object. 每当我通过具有相同属性( obj1obj4 )的对象进行映射时,所有内容均为K。问题是当我想使用某个keys可能不是特定对象)使函数通过arr所有对象进行映射时。

I was thinking about if ('key' in obj) but that wouldn't make function reliable for future, if new keys might be added unless I could analyze all object keys in arr , by creating new array with unique key objects. 我正在考虑if ('key' in obj)但是如果可能添加新的键,除非我可以通过使用唯一键对象创建新数组来分析arr所有对象键,否则可能无法添加功能。 But if object will have 10 keys and there will be 1000+ objects in an array I assume there will be performance issues; 但是,如果对象将具有10个键,并且一个数组中将有1000个以上的对象,那么我认为将存在性能问题。 correct me if i'm wrong. 如果我错了纠正我。

Same goes for .hasOwnProperty() . .hasOwnProperty()

const arr = [
  obj1 = {
    key1: val1,
    key2: val2,
    key3: val3
  },
  obj2 = {
    key3: val3
  },
  obj3 = {
    key1: val4,
    key2: val5,
    key3: val1
  },
  obj4 = {
    key1: val6,
    key2: val7
  }
]

Instead of gussing the keys that an object could have, you can use Object.keys or a for...in loop to dynamically get or loop through keys of an object. 您可以使用Object.keysfor...in循环来动态获取或遍历对象的键,而不用担心对象可能具有的键。 Like this: 像这样:

 var obj = { "key1": 2, "key2": 3, "key-unknown": 5 } console.log("METHOD 1:"); var keys = Object.keys(obj); console.log("obj has these keys: ", keys); console.log("\\nMETHOD 2:"); for(var key in obj) { console.log("'" + key + "' is a key"); } 

Using the above two methods you can safely and dynamically use only the keys that the object has and not use a set of predefined static keys that may or may not be in the object and that could be fewer than what the object actually has. 使用以上两种方法,您可以安全且动态地仅使用对象具有的键,而不使用对象中可能存在或可能不存在的一组预定义静态键,这些预定义静态键可能少于对象实际具有的键。

From a wild guess you may be in need of a function such as; 凭空猜测,您可能需要诸如以下功能:

 function fillMissingKeys(a){ var keys = a.reduce((k,o) => Object.assign(k,Object.keys(o)),[]) .reduce((o,k) => (o[k] = null,o),{}); return a.map(o => Object.assign({},keys,o)); } var arr = [ obj1 = { key1: "val1", key2: "val2", key3: "val3" }, obj2 = { key3: "val3" }, obj3 = { key1: "val4", key2: "val5", key3: "val1", key4: "val8" }, obj4 = { key1: "val6", key2: "val7" } ]; console.log(fillMissingKeys(arr)) 

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

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