Javascript обновляет значения объектов в списке - PullRequest
0 голосов
/ 06 сентября 2018

У меня есть массив объектов

var list = [
{"index" : "1", "name": "abc", "value":123},
{"index" : "2","name": "abc", "value":123},
{"index" : "3","name": "abc", "value":123},
{"index" : "4","name": "abc", "value":123}
];

Пользователь сможет редактировать свойство value. Обратите внимание, что это отображается в приложении SCREENSHOT OF THE SCREEN OF THE APP

Мой вопрос - как вносить изменения в массив при редактировании значений.Любые идеи о том, как это можно сделать?

Вводимые пользователем данные будут числа или с плавающей точкой

Ответы [ 4 ]

0 голосов
/ 06 сентября 2018

с использованием обновления деструктуризации ES6 по свойству индекса (вам следует рассмотреть возможность использования числа в свойстве index и как-то сопоставить его с индексом массива, это может сбить с толку)

let list = [
{"index" : "1", "name": "abc", "value":123},
{"index" : "2","name": "abc", "value":123},
{"index" : "3","name": "abc", "value":123},
{"index" : "4","name": "abc", "value":123}
];


const updateValueByIndex = (list, index, newValue)=>{
    list[index-1]={
      ...list[index-1],
      value:newValue
    }
    //or just list[index-1].value=newValue;
};

updateValueByIndex(list, "1", 33)
console.log(list)
0 голосов
/ 06 сентября 2018

Array.prototype.setName = function(index, value) {
    this.filter(function(v) {
        return v.index == index ? v.name = value : v;
    })
}

Array.prototype.setValue = function(index, value) {
    this.filter(function(v) {
        return v.index == index ? v.value = value : v;
    })
}

var list = [
{"index" : "1", "name": "abc", "value":123},
{"index" : "2","name": "abc", "value":123},
{"index" : "3","name": "abc", "value":123},
{"index" : "4","name": "abc", "value":123}
];

list.setName(2,"qwe");
list.setValue(2,456);


list.setValue(3,789);

console.log(list);
0 голосов
/ 06 сентября 2018

Вот вам и все приложение в ванильном Javascript:

const list = [
{"index" : "1", "name": "abc", "value":123},
{"index" : "2","name": "abc", "value":123},
{"index" : "3","name": "abc", "value":123},
{"index" : "4","name": "abc", "value":123}
];

const app = document.getElementById('app');
const code = document.getElementById('code');

for (const item of list) {
  let div = document.createElement('div');
  let input = document.createElement('input');
  let label = document.createElement('label');
  
  input.type = "number";
  input.id = `input-${item.index}`;
  input.value = item.value;
  input.dataset.index = item.index;
  
  label.setAttribute('for', input.id);
  label.textContent = item.name;
  
  input.addEventListener('input', (e) => {
    list[e.target.dataset.index-1].value = e.target.value;
    code.textContent = JSON.stringify(list);
  })
  
  div.appendChild(input);
  div.appendChild(label);
  console.log(div.outerHTML);
  app.appendChild(div);
}
<div id="app"></div>
<hr />
<code id="code"></code>

Если все, что вам нужно, это функция, которая обновляет заданное свойство с заданным значением по заданному индексу в любом массиве, содержащем объекты, то вы идете (без изменения объектов, которые вам не принадлежат, например Array.prototype):

const list = [
  {"index" : "1", "name": "abc", "value":123},
  {"index" : "2","name": "abc", "value":123},
  {"index" : "3","name": "abc", "value":123},
  {"index" : "4","name": "abc", "value":123}
];

function updateArrayItem(index, prop, value) {
   this.filter(function(i, idx) { return index == i.index ? i[prop] = value : i})
   return this;
}

updateArrayItem.call(list, 1, 'name', 'cba')
updateArrayItem.call(list, 2, 'value', 321)

console.log(list);
0 голосов
/ 06 сентября 2018

Вы бы назвали их списком [i] .property, например,

list[1].name = "dave";
...