搜索&更新嵌套在Javascript数组中的对象的属性

时间:2018-05-08 21:55:51

标签: javascript arrays object functional-programming javascript-objects

假设我有一组嵌套对象,比如

from django.shortcuts import render, redirect
from django.contrib.auth.models import User

def dashboard(request):
    if not request.user.is_authenticated:
        return redirect('index')
    else:
        if request.method == 'POST':
            category = request.POST['category']
            #Here i am using User table because category table is empty
            data = User.objects.all()
            print(data)
            return render(request, 'usecases/dashboard.html', {'data': data})
        else:
            return render(request, 'usecases/dashboard.html')

另一个具有许多属性的对象“foo”,其中一个是“v_id”。 基于foo.v_id的值,我想更新“供应商”数组中的计数或向“供应商”添加新对象。

如果foo.v_id匹配“vendors”数组中的其中一个,则相应的计数会增加1.

示例:

let vendors = [
    {
        v_id: 'red',
        count: 2,
    },
    {
        v_id: 'blue',
        count: 3,
    },
    {
        v_id: 'green',
        count: 1,
    },
];

然后“供应商”将成为:

let foo = {
    user_type: 'Other',
    v_id: 'blue'
};

否则,如果没有匹配的v_id,则会将新对象添加到“vendors”数组中,并使用相应的v_id& count = 1。

示例:

[
    {
        v_id: 'red',
        count: 2,
    },
    {
        v_id: 'blue',
        count: 4,
    },
    {
        v_id: 'green',
        count: 1,
    },
];

然后“供应商”将成为:

let foo = {
    user_type: 'client',
    v_id: 'yellow',
};

我怎样才能有效率和高效率在Javascript中优雅地做到这一点?我知道我可以使用[ { v_id: 'red', count: 2, }, { v_id: 'blue', count: 3, }, { v_id: 'green', count: 1, }, { v_id: 'yellow', count: 1, }, ]; 来获取必须更新的“供应商”中的特定对象,但是如何更新“供应商”数组本身?

2 个答案:

答案 0 :(得分:0)

使用Array.find()v_id搜索数组中的对象。如果对象在数组中,则递增count。如果没有推送新对象:

const vendors = [{"v_id":"red","count":2},{"v_id":"blue","count":3},{"v_id":"green","count":1}];
const foo1 = { user_type: 'Other', v_id: 'blue' };
const foo2 = { user_type: 'client', v_id: 'yellow' };

const addUpdate = (arr, obj) => {
  const current = arr.find((o) => o.v_id === obj.v_id);
  
  if(current) current.count += 1;
  else arr.push({
    v_id: obj.v_id,
    count: 1
  });
};

addUpdate(vendors, foo1);
addUpdate(vendors, foo2);

console.log(vendors);

答案 1 :(得分:0)



function upsert(arr, obj){
  const index = arr.findIndex(item => item.v_id === obj.v_id);
  index === -1 ? arr.push({v_id: obj.v_id, count: 1}) : arr[index].count++
}

let vendors = [{v_id: 'red',count: 2}, {v_id: 'blue',count: 3}, {v_id: 'green',count: 1}];
let foo1 = {user_type: 'Other', v_id: 'blue'};
let foo2 = {user_type: 'client', v_id: 'yellow'};

upsert(vendors, foo1);
upsert(vendors, foo2);

console.log(vendors);