我有一个看起来像这样的对象:
{"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}
答案 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);