简体   繁体   English

使用 JS 在数组中每个 JSON 对象的开头附加一个键值对

[英]Append a key value pair at the start of each JSON object in an array using JS

Essentially I have some data like this:基本上我有一些这样的数据:

[
 {
  "Forename": "Scott",
  "Surname": "Jones",
  "Age": 18,
 },
 {
  "Forename": "Tina",
  "Surname": "Turner",
  "Age": 20,
 },
 {
  "Forename": "Joe",
  "Surname": "Bloggs",
  "Age": 20,
 }
]

I want to know how to add in a key value pair using javascript like so:我想知道如何使用 javascript 添加键值对,如下所示:

[
 {
  "id": 1,
  "Forename": "Scott",
  "Surname": "Jones",
  "Age": 18,
 },
 {
  "id": 2,
  "Forename": "Tina",
  "Surname": "Turner",
  "Age": 20,
 },
 {
  "id": 3,
  "Forename": "Joe",
  "Surname": "Bloggs",
  "Age": 20,
 }
]

I was looking at stuff like mapping through the and adding it to each object but that seemed to only let me add a key value pair to the end of each one.我正在查看诸如通过 映射并将其添加到每个对象之类的东西,但这似乎只能让我在每个对象的末尾添加一个键值对。

Any help / guidance appreciated!任何帮助/指导表示赞赏!

The fastest way to do this I can think of is :我能想到的最快的方法是:

let data = [
 {
  "Forename": "Scott",
  "Surname": "Jones",
  "Age": 18,
 },
 {
  "Forename": "Tina",
  "Surname": "Turner",
  "Age": 20,
 },
 {
  "Forename": "Joe",
  "Surname": "Bloggs",
  "Age": 20,
 }
];

data = data.map((e,i) => Object.assign({id: i}, e));

if you have an array and want to iterate through it, you can use functional methods like forEach or map如果你有一个数组并想遍历它,你可以使用像forEachmap这样的函数方法

var id = 0;
const array = [
 {
  "Forename": "Scott",
  "Surname": "Jones",
  "Age": 18,
 },
 {
  "Forename": "Tina",
  "Surname": "Turner",
  "Age": 20,
 },
 {
  "Forename": "Joe",
  "Surname": "Bloggs",
  "Age": 20,
 }
]
array.forEach((elm) => elm.id = id++)

Anyway your id property is appended at the end because in javascript the order of the properties of objects is not always guaranteed to be maintained.无论如何,您的 id 属性被附加在最后,因为在 javascript 中,并不总是保证保持对象属性的顺序。 Take a look at this question 看看这个问题

The non-numeric keys in a javascript object are ordered by when they are added, so adding a key in a map will place it at the bottom. javascript 对象中的非数字键按添加时间排序,因此在映射中添加键会将其放在底部。 If you want your key to be positioned higher (it honestly should not matter), you would need to create a new object from your existing one.如果您希望您的密钥位于更高的位置(老实说这应该无关紧要),您需要从现有对象创建一个新对象。

We can do that with a function sort of like this:我们可以用这样的函数来做到这一点:

 const obj = { "id": 1, "Surname": "Jones", "Age": 18, }; function objectInsertAt(object, position, key, value) { let i = 0; let result = {}; for (let prop in object) { if (object.hasOwnProperty(prop)) { console.log(prop + ' - ' + i); if (position === i) { result[key] = value; } result[prop] = object[prop]; } i++; } return result; } const newObj = objectInsertAt(obj, 2, 'Forename', 'Scott'); console.log(newObj);

You can read more about the traversal order of object keys here: https://2ality.com/2015/10/property-traversal-order-es6.html#traversing-the-own-keys-of-an-object您可以在此处阅读有关对象键的遍历顺序的更多信息: https : //2ality.com/2015/10/property-traversal-order-es6.html#traversing-the-own-keys-of-an-object

The summary of that article is:那篇文章的摘要是:

Property keys are traversed in the following order:属性键按以下顺序遍历:

  • First, the keys that are integer indices (what these are is explained later), in ascending numeric order.首先,是整数索引的键(稍后解释这些是什么),按数字升序排列。
  • Then, all other string keys, in the order in which they were added to the object.然后,所有其他字符串键,按照它们被添加到对象的顺序。
  • Lastly, all symbol keys, in the order in which they were added to the object.最后,所有符号键,按照它们被添加到对象的顺序。

Many engines treat integer indices specially (even though they are still strings, at least as far as the ES6 spec is concerned).许多引擎特别处理整数索引(即使它们仍然是字符串,至少就 ES6 规范而言)。 Therefore, it makes sense to treat them as a separate category of keys.因此,将它们视为单独的键类别是有意义的。

You can use map您可以使用map

    const array = [ { "Forename": "Scott", "Surname": "Jones", "Age": 18, }, { "Forename": "Tina", "Surname": "Turner", "Age": 20, }, { "Forename": "Joe", "Surname": "Bloggs", "Age": 20, } ]
    const updatedArray = array.map((data,id) => ({...data, id}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM