按字母顺序对JSON进行排序

5

我正在尝试将以下JSON输出到HTML。我已经创建了该对象以及该对象的属性,但是我无法将其输出到HTML。这是我目前的代码。有什么想法吗?

var people;

people = [{
    first_name: 'Don Molloy',
    category: 'academic'
  },
  {
    first_name: 'Pat Quill',
    category: 'academic'
  }
];

console.log(people);

var myObj = JSON.parse(people);
document.getElementById("output-people").innerHTML = myObj.name;
<p id="output-people"></p>

谢谢,

请指定,您想要什么。是命令还是输出还是两者都需要? - Nina Scholz
首先,我想将属性输出到列表中。完成后,下一个难题是按“first_name”字母顺序列出它们。谢谢。 - Kerbol
首先,people 是一个数组而不是 JSON。其次,name 属性在哪里? - Weedoze
这里没有“name”属性;你现在有点在胡乱制造东西。我建议先退后一步,快速搜索如何在js中解析和使用json。需要注意的是,目前还没有json数据。 - Dave Newton
@weedoze - 没错,应该是属性“first_name”,而不是“name”。谢谢。 - Kerbol
3个回答

8

这不是 json 对象,而是一个普通的数组对象。因此,请删除 JSON.parse()。并将输出的 innerHTML dom 更改为 myObj[0].first_name

更新:

对于所有按照 first_name 排序的元素,请尝试使用 myObj.map(a=> a.first_name).sort().join(" and ")

var people;

people = [{
    first_name: 'Don Molloy',
    category: 'academic'
  },
  {
    first_name: 'Pat Quill',
    category: 'academic'
  }
];

people = people.sort((a,b)=> {
var a1 = a.first_name.toLowerCase();
var b1 = b.first_name.toLowerCase();
return a1<b1 ?-1:a1> b1? 1 :0;
})
console.log(people);

var myObj =people;
document.getElementById("output-people").innerHTML = myObj.map(a=> a.first_name).join(" and ")
<p id="output-people"></p>


谢谢 :-) 你会如何按字母顺序列出所有“first_name”属性?例如,先是Don Molloy,然后是Pat Quill。 - Kerbol
在对象数组中进行排序的属性是一个字符串。因此,您的代码将无法正常工作。 - Yosvel Quintero
@Yosvel Quintero - 好的,你认为哪种方法最好? - Kerbol
对象数组可以根据其中一个属性的值进行排序:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort - Yosvel Quintero
@YosvelQuintero。我已经更新了排序函数,可以从对象数组中进行排序。 - prasanth
1
@prasad 很好,那是我唯一的评论。你的回答很完美! - Yosvel Quintero

2
根据你的问题“按字母顺序排序JSON”,你可以首先使用Array.prototype.sort()对数组进行排序,然后填充output变量并使用separator以你想要在html中显示名称的方式。
代码:

const people = [{first_name: 'Don Molloy',category: 'academic'}, {first_name: 'Pat Quill',category: 'academic'}];
const separator = '<br>';

// Sort array of objects by first_name and populate the output with separator
const output = people
  .sort((a, b) => a.first_name.toLowerCase().localeCompare(b.first_name.toLowerCase()))
  .map(user => user.first_name)
  .join(separator);

console.log(people);
document.getElementById('output-people').innerHTML = output;
<p id="output-people"></p>


1

在JS中按字母顺序排序JSON =>

你可以尝试以下方法:

function compareStrings(a, b) {
  // Assuming you want case-insensitive comparison
  a = a.toLowerCase();
  b = b.toLowerCase();

  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

places.sort(function(a, b) {
  return compareStrings(a.first_name, b.first_name);
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接