首页 > 解决方案 > Javascript/Jquery中的Key-Value Pair Json转换与类转换

问题描述

下面是我在 Javascript 中的 JSON 的结构

[
    [{"key": "firstname", "Value": "David"}, {"key": "lastname", "Value": "Smith"} ],
    [{"key": "firstname", "Value": "Allen"}, {"key": "lastname", "Value": "Grover"} ],
    [{"key": "firstname", "Value": "Randy"}, {"key": "lastname", "Value": "Paul"} ]
]

我想通过删除“键”和“值”来在 Javascript/Jquery 中转换它并使它

[
    {"firstname" : "David", "lastname" : "Smith"},
    {"firstname" : "Allen", "lastname" : "Grover"},
    {"firstname" : "Randy", "lastname" : "Paul"}
]

此外,我还想看看我是否可以将此 json 转换为 javascript 对象数组,我可以在其中访问下面的属性会很棒。

var people =[];

people[0].firstname = "David";
people[1].lastname = "Smith";

标签: javascriptjqueryjson

解决方案


您可以使用.map()and.reduce()来实现此功能:

var arr = [
    [{"key": "firstname", "Value": "David"}, {"key": "lastname", "Value": "Smith"} ],
    [{"key": "firstname", "Value": "Allen"}, {"key": "lastname", "Value": "Grover"} ],
    [{"key": "firstname", "Value": "Randy"}, {"key": "lastname", "Value": "Paul"} ]
];

var final = arr.map(keys => {
  // Build the object, by attaching each key to the value
  return keys.reduce((obj, key) => {
    obj[key.key] = key.Value;
    return obj;
  }, {});
});
console.log(final);

现在,关于您的关于车把/反应/html 框架的问题。这是一个示例,说明如何简单地做出反应:

var arr = [
    [{"key": "firstname", "Value": "David"}, {"key": "lastname", "Value": "Smith"} ],
    [{"key": "firstname", "Value": "Allen"}, {"key": "lastname", "Value": "Grover"} ],
    [{"key": "firstname", "Value": "Randy"}, {"key": "lastname", "Value": "Paul"} ]
];

var final = arr.map(keys => {
  // Build the object, by attaching each key to the value
  return keys.reduce((obj, key) => {
    obj[key.key] = key.Value;
    return obj;
  }, {});
});

class App extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      data: props.data
    };
  }
  
  render() {
    return React.createElement('div', null,
      this.state.data.map(name =>
        React.createElement('div', null,
          `Name: ${name.firstname} ${name.lastname}`
        )
      )
    );
  }
}

ReactDOM.render(React.createElement(App, {data: final}), document.getElementById("root"));
<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>

注意:这段代码相当难看,因为我不得不求助于 using ,使用JSXReact.createElement时不需要其中的一些东西。


推荐阅读