You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JSON对象的两个值合并为单个JavaScript数组元素?

解决JSON对象转单元素数组的问题

Hey there! Your approach is on the right track, but there's a small mistake in how you're accessing the object properties that's keeping it from working correctly. Let's fix that and also cover a more flexible approach for future cases.

First, the corrected version of your code

Your JSON object uses key1 and key2 as property names, but you tried to access obj.value1 and obj.value2—that's the issue! Here's the fixed code:

// 假设countrylist是你的JSON字符串(注意要加引号包裹)
var countrylist = '{"key1": "value1", "key2": "value2"}';
var obj = JSON.parse(countrylist);
// 用正确的属性名key1和key2
var my_array = [obj.key1 + " " + obj.key2];

console.log(my_array); // 输出: ["value1 value2"]

A more flexible approach (for any number of keys)

If you ever have more than two key-value pairs and want to merge all values into a single array element without hardcoding each property, you can use Object.values() to get all values at once, then join() to combine them with spaces:

var countrylist = '{"key1": "value1", "key2": "value2"}';
var obj = JSON.parse(countrylist);
// 获取所有值并拼接,再放入数组
var my_array = [Object.values(obj).join(" ")];

console.log(my_array); // 同样输出: ["value1 value2"]

This way, even if you add more keys later (like key3: "value3"), the code will automatically merge all values into one string in the array—no need to update the property references!

内容的提问来源于stack exchange,提问作者Fathah Cr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:42:31