覆盖排序索引

时间:2018-09-15 15:54:17

标签: javascript sorting

从后端,我将具有排序索引(随机数在1到999之间)和具有由其索引排序的项ID的项列表数组的对象传递给对象,例如:

var x =row.insertCell(1);
var y = document.createElement("INPUT");
y.setAttribute("type", "text");
x.appendChild(y);

使用UI用户可以更改反映在itemList数组中的元素的顺序。在UI中单击“保存”按钮后,我需要正确地重新分配现有的排序索引,并将仅索引已更改的元素发送到后端。因此,例如,如果用户将if let configView = UIView.fromNib("SwitchConfigurationView") as? SwitchConfigurationView{ self.view.addSubview(configView) //workaround - cell will be passed in later if let cell = collectionView.visibleCells.first{ UIView.transition(from: cell, to: configView, duration: 1.0, options: .curveEaseInOut, completion: { success in ///... }) } configView.translatesAutoresizingMaskIntoConstraints = false let topConstraint = NSLayoutConstraint(item: configView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0) view.addConstraint(topConstraint) let trailingConstraint = NSLayoutConstraint(item: configView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1.0, constant: 0) view.addConstraint(trailingConstraint) let leadingConstraint = NSLayoutConstraint(item: configView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0) view.addConstraint(leadingConstraint) let bottomConstraint = NSLayoutConstraint(item: configView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0) view.addConstraint(bottomConstraint) } 设置为第二个位置,则itemList将为{ items: { 1: { sort: 131, name: 'Item 1' }, 2: { sort: 22, name: 'Item 2' }, 3: { sort: 440, name: 'Item 3' }, 4: { sort: 80, name: 'Item 4' } }, itemList: [2, 4, 1, 3] } ,并且发送到后端的数据应为:

item 2

如果用户将[4, 2, 1, 3]设置为第四个位置,则itemList将为{ 2: { sort: 80 }, 4: { sort: 22 } } ,并且发送到后端的数据应为:

item 2

如何实现该功能?

1 个答案:

答案 0 :(得分:1)

这是您如何实现的

var getUpdatedItems = (function() { 

    var items = {
        1: {
            sort: 131,
            name: 'Item 1'
        },
        2: {
            sort: 22,
            name: 'Item 2'
        },
        3: {
            sort: 440,
            name: 'Item 3'
        },
        4: {
            sort: 80,
            name: 'Item 4'
        }
    },
    itemsList = [];

    function _getUpdatedItems(newItemsList) {
        itemsList = Object.entries(items).sort(([,a], [,b]) => a.sort - b.sort).map(([data]) => data);

        var dataToSend = {};
        newItemsList.forEach((key, index) => key != itemsList[index] && (dataToSend[key] = { sort: items[itemsList[index]].sort }))

        console.log(dataToSend)
    }

    return _getUpdatedItems;

})()

// you can test with below test and you will get expected result
getUpdatedItems([4,2,1,3]) 

getUpdatedItems([4,1,3,2])