简体   繁体   English

如何在javascript中只获取嵌套object中的键值对

[英]How to get only key value pairs in nested object in javascript

let Ar=[
{
      info:{
          name:"Sai",
          age:24
      },
    grade:'A'
},    
{
    name:"Satish",
    grade:'B',
    info:{
        place:"Hyd",
        company:'Company1'
    },
    info2:{
        place2:"Hyderabad",
        company2:'Company2'
    }
}

] ]

**Output should be key values pairs only ** **输出应该只是键值对**

[
    {
        "name": "Sai",
        "age": 24,
        "grade": "A"
    },
    {
        "name": "Satish",
        "grade": "B",
        "place": "Hyd",
        "company": "Company1",
        "place2": "Hyderabad",
        "company2": "Company2"
    }
]

How we can get only key value pairs form the object and nested object

*Current solution I have like this But do we have more optimized code to get the only key value pairs from an object. I have used Object.keys(obj) and Object.entries(obj) methods to achieve * *我目前的解决方案是这样的但是我们是否有更优化的代码来从 object 中获取唯一的键值对。我使用了 Object.keys(obj) 和 Object.entries(obj) 方法来实现 *

let fr=Ar.map((A)=>{
    let test=[];
  let en= Object.keys(A).map((item) => {
  if (typeof A[item] === "object") {
     Object.entries(A[item]).map((i)=>{test.push(i)})
  } else {
    return test.push([item, A[item]]);
  }
});  
    
    return test;
})
    
let finalAnswer=fr.map((item)=>{
    return Object.fromEntries(item)
})
 console.log("Spread Print",finalAnswer)

Is there any better solution than me?有没有比我更好的解决方案?

You can use this你可以用这个

let fr=Ar.map((A)=>{
let test={};


Object.keys(A).forEach((item) => {

if (typeof A[item] === "object") {
 test={...test,...A[item]};
  } else {
test[item]=A[item]


 }

} return test }); } return test });

The below may be one possible solution (using recursion) to achieve the desired objective.以下可能是实现预期目标的一种可能解决方案(使用递归)。

Please note that if there are duplicate keys in nested levels, only the latest/last key-value pair will be retained.请注意,如果嵌套级别中存在重复的键,则只会保留最新/最后的键值对。

Code Snippet代码片段

 // recursive method to transform nested objects const recTxf = parm => { if (Array.isArray(parm)) { // if key-value pair array const [k, v] = parm; // either recurse to nested, or return key-value pair if (typeof v === 'object') return recTxf(v); else return { [k]: v }; } else return { // otherwise, it is object...Object.entries(parm) // iterate over key-value pairs.reduce( (acc, itm) => ({ // use "reduce" to accumulate/aggregate...acc, ...recTxf(itm) // aggregate results of the recursive calls }), {} ) }; }; // method to iterate over the array const myTransform = arr => arr.map(ob => recTxf(ob)); let Ar = [ { info: { name: "Sai", age: 24 }, grade: 'A' }, { name: "Satish", grade: 'B', info: { place: "Hyd", company: 'Company1' }, info2: { place2: "Hyderabad", company2: 'Company2' } } ]; console.log(myTransform(Ar));
 .as-console-wrapper { max-height: 100%;important: top: 0 }

Explanation解释

Inline comments are provided in the snippet above.上面的代码片段中提供了内嵌注释。

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

相关问题 如何在 JavaScript 中将嵌套对象数组转换为具有键值对的对象 - How to convert an array of nested objects to an object with key, value pairs in JavaScript 如何在javascript中获取数组object中的键值对 - How to get key value pairs in array object in javascript 尝试在对象中的特定键值对上使用 JavaScript 嵌套循环 - Attempting to use a JavaScript nested loop on specific key value pairs in an object javascript对象键值对 - javascript object key value pairs 如何遍历嵌套的JSON对象并在Javascript中保存多个键值对 - How to loop through a nested JSON object and save the multiple key-value pairs in Javascript (递归)如何从具有嵌套对象和数组的对象中获取所有键/值对 - (Recursion) How to get all key/value pairs from an Object with nested objects and arrays 如何在 JavaScript 中的嵌套 Arrays 中插入键值对 - How to Insert Key Value Pairs inside Nested Arrays in JavaScript 如何在嵌套数组中的键值对中输出键 - How to output keys in key value pairs in nested arrays JavaScript 如何使用键值对将嵌套的JSON数据结构展平为对象 - How to flatten a nested JSON data structure into an object with key value pairs 迭代javascript对象以获取键值对 - Iterating through a javascript object to get key-value pairs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM