如何为JavaScript对象的每个唯一值创建ID?

时间:2019-06-13 14:43:32

标签: javascript

我有一个看起来像这样的对象:

{"JUN", "100", "1"},
{"JULY", "200", "2"},
{"AUG", "300", "3"},
{"SEP", "400", "4"},
{"OCT", "500", "5"},
{"NOV", "600", "6"}

对于color_property的每个唯一实例,我想在object2中创建一个新的id属性。

object1 = {property: some_value, color_property: yellow},
          {property: some_value, color_property: green},
          {property: some_value, color_property: green}, 
          {property: some_value, color_property: red}, 
          {property: some_value, color_property: yellow}

1 个答案:

答案 0 :(得分:1)

您可以为每种颜色使用相同的id哈希表。

var array = [{ property: 'some_value', color_property: 'yellow' }, { property: 'some_value', color_property: 'green' }, { property: 'some_value', color_property: 'green' }, { property: 'some_value', color_property: 'red' }, { property: 'some_value', color_property: 'yellow' }],
    counter = 0,
    hash = {},
    result = array.map(o => Object.assign(
        {},
        o,
        { id: hash[o.color_property] = hash[o.color_property] || ++counter }
    ));

console.log(result);