如何在JavaScript中获取所有属性的对象路径。

huangapple go评论76阅读模式
英文:

How to get object path for all property in js

问题

如何获取下面对象中所有属性的对象路径

{
    employeeInfo: {
        address1: '2nd street',
        address2: 'eb colony',
        city: 'coimbatore'
    }
}

期望结果

{
    fields: [
        {
            fieldId: 'employeeInfo.address1',
            value: '2nd street'
        },
        {
            fieldId: 'employeeInfo.city',
            value: 'coimbatore'
        },
        {
            fieldId: 'employeeInfo.country.countryname',
            value: 'india'
        },
        {
            fieldId: 'employeeInfo.country.isoalphacode2',
            value: 'IN'
        }
    ]
}

Jason路径查找和解析应该可以动态工作。

英文:

How to get the object path for all properties from the below object

  {
    employeeInfo: {
        address1: '2nd street',
        address2: 'eb colony',
        city: 'coimbatore'
    }
 }

Expected result

 {
fields: [
    {
        fieldId: 'employeeInfo.address1',
        value: '2nd street'
    },
    {
        fieldId: 'employeeInfo.city',
        value: 'coimbatore'
    },
    {
        fieldId: 'employeeInfo.country.countryname',
        value: 'india'
    },
    {
        fieldId: 'employeeInfo.country.isoalphacode2',
        value: 'IN'
    }
]

}

Jason path finding and parsing should work dynamically

答案1

得分: 2

为了动态查找和解析给定对象中所有属性的对象路径,您可以使用递归函数。以下是一个示例实现:

function getObjectPath(obj, prefix = '', result = []) {
  for (let key in obj) {
    if (typeof obj[key] === 'object') {
      getObjectPath(obj[key], prefix + key + '.', result);
    } else {
      result.push({
        fieldId: prefix + key,
        value: obj[key]
      });
    }
  }
  return result;
}

// 示例用法
const data = {
  employeeInfo: {
    address1: '2nd street',
    address2: 'eb colony',
    city: 'coimbatore',
    country: {
      countryname: 'india',
      isoalphacode2: 'IN'
    }
  }
};

const result = {
  fields: getObjectPath(data)
};

console.log(result);

此代码定义了getObjectPath函数,该函数递归遍历对象并构建每个属性的对象路径。它接受三个参数:要遍历的对象(obj)、当前前缀(初始化为空字符串)和存储字段对象的结果数组。

在函数内部,它遍历对象的键。如果键的值是另一个对象,则使用更新后的前缀(包括当前键)递归调用getObjectPath。如果值不是对象,则将一个字段对象添加到结果数组中,其中fieldId是前缀和当前键的连接,value是属性的值。

在示例用法中,我们提供了data对象,并将getObjectPath(data)的结果分配给结果对象的fields属性。

输出将显示在控制台中,包含数据对象中每个属性的对象路径和相应的值的预期结果。

英文:

To dynamically find and parse the object path for all properties in the given object, you can use a recursive function. Here's an example implementation in

function getObjectPath(obj, prefix = '', result = []) {
  for (let key in obj) {
    if (typeof obj[key] === 'object') {
      getObjectPath(obj[key], prefix + key + '.', result);
    } else {
      result.push({
        fieldId: prefix + key,
        value: obj[key]
      });
    }
  }
  return result;
}

// Example usage
const data = {
  employeeInfo: {
    address1: '2nd street',
    address2: 'eb colony',
    city: 'coimbatore',
    country: {
      countryname: 'india',
      isoalphacode2: 'IN'
    }
  }
};

const result = {
  fields: getObjectPath(data)
};

console.log(result);

This code defines the getObjectPath function, which recursively traverses the object and builds the object path for each property. It takes three parameters: the object to traverse (obj), the current prefix (initialized as an empty string), and the result array to store the field objects.

Within the function, it iterates over the keys of the object. If the value of a key is another object, it calls getObjectPath recursively with an updated prefix (including the current key). If the value is not an object, it adds a field object to the result array with the fieldId as the concatenation of the prefix and the current key, and the value as the value of the property.

In the example usage, we provide the data object and assign the result of getObjectPath(data) to the fields property of the result object.

The output will be displayed in the console, containing the expected result with the object path and corresponding values for each property in the data object.

答案2

得分: 0

const obj =   {
    employeeInfo: {
        address1: '2nd street',
        address2: 'eb colony',
        city: 'coimbatore'
    }
 }

console.log(getFields(obj))

function getFields(obj) {
  const fields = []

  req(obj, [])

  return { fields }

  function req(o, str) {
    if (typeof o !== 'object') {
      fields.push({
        fieldId: str.join('.'),
        value: o
      })
      return
    }
    for (const key in o) {
      req(o[key], [...str, key])
    }
  }
}
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const obj =   {
    employeeInfo: {
        address1: &#39;2nd street&#39;,
        address2: &#39;eb colony&#39;,
        city: &#39;coimbatore&#39;
    }
 }
 
console.log(getFields(obj))

function getFields(obj) {
  const fields = []
  
  req(obj, [])
  
  return { fields }
  
  function req(o, str) {
    if (typeof o !== &#39;object&#39;) {
      fields.push({
        fieldId: str.join(&#39;.&#39;),
        value: o
      })
      return
    }
    for (const key in o) {
      req(o[key], [...str, key])
    }
  }
}

<!-- end snippet -->

答案3

得分: 0

这是另一个答案:

let data = {
    employeeInfo: {
        address1: '2nd street',
        address2: 'eb colony',
        city: 'coimbatore'
    }
}

const createObject = (obj, prefix = '', result = []) => {
    for (key in obj) {
        if (typeof obj[key] === 'object') {
            createObject(obj[key], key, result)
        } else {
            result.push({
                fieldId: prefix + "." + key,
                value: obj[key]
            })
        }
    }
    return result;
}

const output = {
    fields: createObject(data)
};

console.log(output);

希望这对你有帮助!

英文:

Here is another answer:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let data = {
    employeeInfo: {
        address1: &#39;2nd street&#39;,
        address2: &#39;eb colony&#39;,
        city: &#39;coimbatore&#39;
    }
 }



 const createObject = (obj,prefix = &#39;&#39;,result =[])=&gt;{
     for(key in obj){
       
        if(typeof obj[key] === &#39;object&#39;){
            createObject(obj[key],key,result)
        }else{
           result.push({
            fieldId: prefix+&quot;.&quot;+key,
            value: obj[key]
           }) 
        }
    }
    return result;

}

const output = {
  fields: createObject(data)
};



console.log(output);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月13日 17:08:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76677702.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定