javascript - 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";
解决方案
您可以使用.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
时不需要其中的一些东西。
推荐阅读
- php - Laravel 处理数组并循环遍历关联数组
- r - R 中的非等值连接与 data.table - 反引号列名问题
- git - 如何在另一个功能中测试 git flow 功能
- c# - 从 try catch 语句中捕获异常消息以显示在 asp.net 中的 jquery 对话框中
- html - 如何从角度 6 中的多个选择下拉列表中获取多个值?
- mysql - 在 Windows 10 上安装 mysql server 8.0 失败
- spring - Spring 上下文启动期间的就绪探测
- laravel - laravel 雄辩的关系使用“with”,“whereHas”和“whereIn”子句
- elasticsearch - 弹性搜索错误 56
- node.js - 使用 .bat 在 Windows 上调度 node.js 命令