显示对象的键和值,并转换为 HTML 链接



我正在尝试从数组中获取键和值并将其转换为链接列表。

这是我的变量

var MyObj = [{
"1": "Val_1",
"2": "Val_2",
"3": "Val_3",
}];

这就是我试图让链接看起来像的样子

<a href="/?categories='+ MyObj[0].key +'&type='+MyObj[0].value+'/">MyObj[0].value</a>

我一直在尝试各种方法,但没有具体结果,我最接近的是控制台中的输出.log该状态 [对象对象]

如果要获取对象的键,则应使用Object.keys方法。

然后,您可以循环访问对象的键并构建链接。为了返回链接数组,最好使用Array#map方法:

var MyObj = {
"1": "Val_1",
"2": "Val_2",
"3": "Val_3",
};
var links = Object.keys(MyObj).map(function(key) {
return '<a href="/?categories='+ key + '&type=' + MyObj[key] + '/">' + MyObj[key] + '</a>';
});
console.log(links);

您可以运行代码段并查看结果。

或者,在 ES6 语法中:

const links = Object.keys(MyObj).map(key => `<a href="/?categories=${key}&type=${MyObj[key]}/">${MyObj[key]}</a>`);

如果我理解正确的话。您可以实现您想要的,如下所示:

//declare variable
var MyObj ={
"1": "Val_1",
"2": "Val_2",
"3": "Val_3",
};   
//declare an array where you are going to store your elements
var newArray = [];
for(key in MyObj){ //loop over keys of MyObj object variable 
//string variable where we concatenate key and value as below
var str = "/?categories="+ key +"&type="+MyObj[key]+"/";
newArray.push(str);//we push this string value to the newArray declared outside of the loop
}
console.log(newArray);//to see the result on the console
//let me know if you have more questions in the comments

这是一个对象,而不是数组。

数组使用以下语法:

var myArr = ["Val_1", "Val_2"]

您可以使用 for 循环轻松遍历数组

var myArray = ["val_1", "val_2"]
for(let i = 0; i < myArray.length; i++){
let url = "<a href="/?categories=" + i +"&type="+myArray[i]+"">" +myArray[i]+"</a>"
console.log(url)
}

如果我正确理解了这个问题,你应该使用 $.param((。 它会将您的对象转换为 url 字符串

最新更新