简体   繁体   English

如何从具有不同值的两个对象返回键和值

[英]How to return the keys & values from two objects with different values

How would I loop over two objects and only return a list of the keys & values that were different?我将如何遍历两个对象并返回不同的键和值的列表?

let list = [];

let previousObject = {
    key: 'key_1',
    name: 'Previous name',
    age: '30',
    location: '12345 Main St.',
    height: '77',
    weight: '215',
    ...
}

let newObject = {
    key: 'key_1',
    name: 'New name',
    age: '25',
    location: '54321 Main St.',
    height: '77',
    weight: '195',
    ...
}

I would like the list to return...我希望列表返回...

list = [{ name: 'New name', age: '25', location: '54321 Main St.' }]

Things to consider:需要考虑的事项:

  • The previousObject might contain more keys than the newObject previousObject可能包含比 newObject 更多的键
  • Checking for these differences might happen more than once per user session每个用户可能不止一次检查这些差异 session

In your example list is an array with only one object containing all the differences.在您的示例list是一个数组,其中只有一个 object 包含所有差异。 To get that object, you can do this:要获得 object,您可以这样做:

 let list = []; let previousObject = { key: 'key_1', name: 'Previous name', age: '30', location: '12345 Main St.', height: '77', weight: '215', } let newObject = { key: 'key_1', name: 'New name', age: '25', location: '54321 Main St.', height: '77', weight: '195', } let diff = {} for (const key in newObject) { if (previousObject[key].= newObject[key]) { diff[key] = newObject[key] } } console.log(diff)

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

相关问题 如何返回一个对象数组,返回与某些特定键匹配的对象:来自两个不同对象的值? - how to return an array of objects returning the objects that matched some specific key:values from two different objects? 如何使用 javascript 从对象数组中执行添加相同键的对象值并返回唯一对象? - How to perform addition of same keys' values of objects and return unique objects from array of objects using javascript? 打字稿:如何从 2 组不同的对象中获取具有相同属性值但键不同的对象 - typescript: How to get objects with the same property values but different keys from 2 different sets of Objects 比较两个对象的值和键 - Comparing values and keys of two objects 从两个不同的对象获取对应的值 - Getting corresponding values from two different objects Javascript对象:这两个值有何不同? - Javascript objects: how are these two values different? 比较具有不同键的对象的特定值 Javascript - compare specific values from objects with different keys Javascript 从JSON中不同对象的相同键中选择值 - To select values from the same keys in different objects in JSON 根据两个键从对象数组中获取唯一值 - Get unique values from an array of objects based on two keys 如何使用不同的键从对象中提取2个值 - How to extract 2 values from an object with different keys
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM