【问题标题】:Add unique generated Identifier on array of json object在 json 对象数组上添加唯一生成的标识符
【发布时间】:2019-03-26 21:58:33
【问题描述】:

如何在下面的 JSON 中添加 uniqueId 字段。该数组数据量大,需要在已有数组上动态唯一标识。

[{"title":"Accompanying"},{"title":"Chamber music"},{"title":"Church 

音乐"}......]

所以,这应该如下所示:

[{"title":"Accompanying", "uniqueId": 1},{"title":"Chamber music", "uniqueId": 2}..]

uniqueId- 类型、数字或 guid。

注意:不知道“标题”或其他字段可能是什么,因此无法按名称映射字段。

【问题讨论】:

  • 使用累加器,遍历数组并在对象中添加每个对象的累加器值

标签: javascript arrays json ecmascript-5


【解决方案1】:

如果这是一次性的,您可以执行以下操作:

const newArray = oldArray.map((x, i) => ({
    // If the object is dynamic you can spread it out here and add the ID
    ...x,
    // Use the items index in the array as a unique key
    uniqueId: i,
}));

如果您想改用 GUID 生成器(我建议这样做),只需将 i 替换为您用来生成 GUID 的任何内容,并确保在添加到集合时为数据生成新的 GUID .

const newArray = oldArray.map((x) => ({ ...x, uniqueId: generateGuid() }));

const yourDynamicObjects = [
    {
        title: 'A title',
        author: 'A. Author'
    },
    {
        foo: 'bar',
    },
    {
        quotient: 2,
        irrational: Math.sqrt(2)
    }
];

const updatedData = yourDynamicObjects.map((x, i) => ({ ...x, uniqueId: i, }));

console.log(updatedData);

【讨论】:

  • title: x.title, // 这实际上是未知的。由于它的动态数组是从外部 API 接收的,我只需要在对象的动态数组上注入唯一的 id。
  • 您可以为此使用扩展运算符 (...)。我会更新我的答案
【解决方案2】:

您可以使用map & 在它的回调函数中使用index 参数来创建uniqueId

item.title 实际上并不知道它的动态数组,因此,可以 不映射到特定的字段名

在这种情况下,使用Object.keys 来获取所有键的数组。然后循环它并将密钥添加到新对象

let k = [{
  "title": "Accompanying"
}, {
  "title": "Chamber music"
}, {
  "title": "Church"
}]
let getArrayKey = Object.keys(k[0]);
let n = k.map(function(item, index) {
  let obj = {};
  getArrayKey.forEach(function(elem) {
    obj[elem] = item[elem];
  })
  obj.uniqueId = index + 1
  return obj;
});

console.log(n)

你也可以使用扩展运算符

let k = [{
  "title": "Accompanying"
}, {
  "title": "Chamber music"
}, {
  "title": "Church"
}]

let n = k.map(function(item, index) {
  return Object.assign({}, { ...item,
    uniqueId: index + 1
  })

});

console.log(n)

【讨论】:

  • title:item.title 实际上并不是它的动态数组,因此无法映射到特定的字段名称。
【解决方案3】:

我会选择一个简单的 for 循环

let myArray = [{"title":"Accompanying"},{"title":"Chamber music"},{"title":"Church music"}];
let i = 0, ln = myArray.length;
for (i;i<ln;i++){
  myArray[i].uniqueId = i+1;
}

console.log(myArray);

【讨论】:

    猜你喜欢
    • 2023-02-06
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多