[英]Javascript: How to make array from object with key value pairs as strings?
I have an object, from which an array has to be made, where key + value pairs are converted to strings.我有一个 object,必须从中创建一个数组,其中键 + 值对转换为字符串。
var obj = {'x': 1, 'y': 2, 'z':3};
I have tried to convert the content to strings:我试图将内容转换为字符串:
var joined = Object.entries(obj ).join(' ');
"x,1 y,2 z,3"
and to an array of arrays和 arrays 的数组
var entries = Object.entries(obj);
But it is not exactly what I need但这并不是我所需要的
My ideal result is我理想的结果是
var arrayFromObject = ['x 1', 'y 2', 'z 3'];
I can probably flatten the array of arrays but maybe there is a better solution?我可能可以展平 arrays 的数组,但也许有更好的解决方案?
You can get the desired output using .map()
, .join()
and Object.entries()
:您可以使用.map()
、 .join()
和Object.entries()
获得所需的 output :
[key, value]
pairs of a given object's properties using Object.entries()
.使用Object.entries()
获取给定对象属性的[key, value]
对数组。.map()
over the array values returned in first step and use .join()
to get the string in desired format.使用.map()
遍历第一步返回的数组值,并使用.join()
获取所需格式的字符串。 const obj = {'x': 1, 'y': 2, 'z': 3}; const array = Object.entries(obj).map(a => a.join(' ')); console.log(array);
If you know you have a KVP set, you can do something like如果你知道你有一套 KVP,你可以做类似的事情
const obj = {'x': 1, 'y': 2, 'z':3};
const result = Object.entries(obj).map(entry => `${entry[0]} ${entry[1]}`);
//(3) ["x 1", "y 2", "z 3"]
Object.keys(obj).map(x => `${x} ${obj[x]}`)
Explanation解释
Object.keys(obj)
returns ["x", "y", "z"]
and map
then maps every key to a template literal ${x} ${obj[x]}
where obj[x]
is the value ( y
is mapped to y 2
) Object.keys(obj)
返回["x", "y", "z"]
并且map
然后将每个键映射到模板文字${x} ${obj[x]}
其中obj[x]
是值 ( y
映射到y 2
)
const obj = {'x': 1, 'y': 2, 'z':3}; const array = Object.entries(obj).map(a => a.join(' ')); console.log(array);
You can use for loop for your desired output, you could've used map but it creates performance issues if the list is large.您可以为所需的 output 使用 for 循环,您可以使用 map,但如果列表很大,它会产生性能问题。
let obj = { x: 1, y: 2, z: 3 }; let outputArray = []; for (let i = 0; i < Object.keys(obj).length; i++) { outputArray.push(Object.keys(obj)[i]+' '+Object.values(obj)[i]); } console.log(outputArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.