javascript 如何在 React.js 中获取 JSON 对象的键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48156381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:51:26  来源:igfitidea点击:

How to get Keys and values of a JSON object in React.js

javascriptjsonreactjsobject

提问by user2138675

I am new to react and trying to implement all the key and values of a JSON object in my web page. I have a below JSON structure. I want all the keys and values to be printed in my web page where key should be printed as labels.

我是新手,并试图在我的网页中实现 JSON 对象的所有键和值。我有一个下面的 JSON 结构。我希望所有的键和值都打印在我的网页中,其中键应该打印为标签。

{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4":{
       "k1": "val1",
        "k2": {
        "p1": "v1",
        "p2": "v2",
        "p3": "v3"
            }
          }
        }

I have written the below code to get the keys and values of this JSON.

我编写了以下代码来获取此 JSON 的键和值。

getValues() {
        let arr = [];
        arr = Object.keys(this.props.myArr).map(key =>
            <div key={this.props.data[key]} className="row">
                <div className="col-xs-6">{key}</div>
                <div className="col-xs-6">{this.props.myArr[key]}
                </div>
            </div>

        )
        return arr;
    }
render() {
    return (
        <div>
            <Header />
            <div className="content">
                {this.getValues()}
            </div>
        </div>
    )
}

}

}

props.myArr has the entire object.

props.myArr 拥有整个对象。

I am able to print the keys and values but not the nested object under key4(p1,p2,p3). I want all the keys along with its values to be printed one after another in my web page. Can someone tell me where am i going wrong and how to access all the keys (as labels) and values of the JSON object.

我可以打印键和值,但不能打印 key4(p1,p2,p3) 下的嵌套对象。我希望在我的网页中一个接一个地打印所有键及其值。有人可以告诉我我哪里出错了以及如何访问 JSON 对象的所有键(作为标签)和值。

Edited-

编辑-

const myObj = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
  "key4": {
    "k1": "val1",
    "k2": {
      "p1": "v1",
      "p2": "v2",
      "p3": "v3"
    }
  }
}


class Details extends React.component{
constructor(){
  this.getValues = this.getValues.bind(this);
}
getValues() {
        let arr = [];
        arr = Object.keys(myObj).map(key =>
            <div key={myObj[key]} className="row">
                <div className="col-xs-6">{key}</div>
                <div className="col-xs-6">{myObj[key]}
                </div>
            </div>

        )
        return arr;
    }

generateData(myObj) {

        const newData = Object.keys(myObj).reduce((result, currentKey) => {
          if (typeof myObj[currentKey] === 'string' || myObj[currentKey] instanceof String) {
            const elementToPush = getValues(currentKey, myObj[currentKey]);
            result.push(elementToPush);
          } else {
            const nested = generateData(myObj[currentKey]);
            result.push(...nested);
          }
          return result;
        }, []);
        return newData;
      }

render() {
    return (
        <div>
            <Header />
            <div className="content">
                {this.generateData(myObj)}
            </div>
        </div>
    )
}
}

}

}

P.S I am using getValues with map function to retrieve first level of key and values as the provided syntax by you under generateElement() gives me error.

PS 我正在使用 getValues 和 map 函数来检索第一级键和值,因为您在 generateElement() 下提供的语法给了我错误。

采纳答案by Sagiv b.g

What you need here is recursion.

你在这里需要的是递归。

Though, there is something missing in your design, you are not defining the exact condition for when should the program actually extract the value.

虽然您的设计中缺少一些东西,但您并没有定义程序何时实际提取值的确切条件。

For example, lets define that if a valueof a given keyisa string, then we will render it to the page.

例如,让我们定义如果value给定的 akey一个字符串,那么我们将把它渲染到页面上。

Such condition will look something like this:

这种情况看起来像这样:

if (typeof data[key] === 'string' || data[key] instanceof String)

Then with this decision, you can write a function that will take a data object and recursively will go over the object's keys, based on the condition above, it will return the valueOranother call to the same function with the valueas the new data object.

然后有了这个决定,您可以编写一个函数,该函数将接受一个数据对象并递归地遍历该对象的键,基于上述条件,它将返回value或者对与value新数据对象相同的函数的另一个调用。

The function will look something along this block of code:

该函数将沿此代码块查找:

function generateData(data) {
  const newData = Object.keys(data).reduce((result, currentKey) => {
    if (typeof data[currentKey] === 'string' || data[currentKey] instanceof String) {
      result.push(currentKey);
    } else {
      const nested = generateData(data[currentKey]);
      result.push(...nested);
    }
    return result;
  }, []);
  return newData;
}

I'm using .reducehere to build a new array. and as mentioned above, i will push to the new array either the keyor the result of a recursive call to the function with the valueas the new data object, of course based on the condition mentioned above.
Note, that the recursive call will return an array, so i'm using the spread syntaxto extract it's members.

我在.reduce这里使用来构建一个新数组。并且如上所述,我将key使用value作为新数据对象的函数的递归调用的结果或结果推送到新数组,当然基于上述条件。
请注意,递归调用将返回一个数组,因此我使用扩展语法来提取它的成员。

Now, we want our keyand valueto get rendered to the DOM.
So instead to just push the keyor value, we can push an element.

现在,我们希望我们的keyvalue被渲染到DOM.
因此,我们可以推送一个元素,而不是仅仅推送keyor value

Here is a full running example:

这是一个完整的运行示例:

const myData = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
  "key4": {
    "k1": "val1",
    "k2": {
      "p1": "v1",
      "p2": "v2",
      "p3": "v3"
    }
  }
}

const generateElement = (key,value) => {
  return (
    <div key={key} className="row">
      <div className="col-xs-6 ins-label">{key}</div>
      <div className="col-xs-6">{value}</div>
    </div>
  );
}

function generateData(data) {
  const newData = Object.keys(data).reduce((result, currentKey) => {
    if (typeof data[currentKey] === 'string' || data[currentKey] instanceof String) {
      const elementToPush = generateElement(currentKey, data[currentKey]);
      result.push(elementToPush);
    } else {
      const nested = generateData(data[currentKey]);
      result.push(...nested);
    }
    return result;
  }, []);
  return newData;
}

class App extends React.Component {
  render() {
  const { data } = this.props;
    return (
      <div>
        {generateData(data)}        
      </div>
    )
  }
}

ReactDOM.render(<App data={myData} />, document.getElementById('root'));
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>