[英]Javascript: map Array of Objects with unknown keys
I have an array of objects with keys that have different names.我有一组具有不同名称的键的对象。
let array = [{"obj1": 1, "obj2": 2}, {"obj3": 3}]
I want to be able to display on the front (react-native) the key and the value.我希望能够在前面(react-native)显示键和值。 I tried doing so with a map and object.entries but it is not working (Error: Objects are not valid as a React child . If you meant to render a collection of children, use an array instead.):
我尝试使用 map 和 object.entries 这样做,但它不起作用(错误:对象作为 React child 无效。如果您打算渲染一组孩子,请改用数组。):
{Object.entries(array).map(([key, val] = entry) => {
return (<Text>{[key, val]}</Text>)
})
How could I display simply in a Text the key and the value of each object?如何在 Text 中简单地显示每个对象的键和值?
You should reduce the array, spread the entries, and then flatten.您应该减少数组,展开条目,然后展平。 The result will be an array of key-value pairs.
结果将是一个键值对数组。
const array = [{ "obj1": 1, "obj2": 2 }, { "obj3": 3 }] const keyValuePairs = array .reduce((pairs, obj) => [...pairs, Object.entries(obj)], []) .flat(); keyValuePairs.forEach(([key, val]) => console.log(key, val));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.