programing tip

jQuery를 사용하여 JavaScript 객체에서 항목 추가 / 제거

itbloger 2020. 9. 23. 07:22
반응형

jQuery를 사용하여 JavaScript 객체에서 항목 추가 / 제거


다음과 같은 JavaScript 개체가 있습니다.

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "2", name: "Witches of Eastwick", type: "comedy"},
    {id: "3", name: "X-Men", type: "action"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]};

이 목록에 항목을 추가 / 제거하려면 jQuery를 사용하여 어떻게해야합니까? 클라이언트는이 목록을 동적으로 수정할 수 있기를 원합니다.


먼저, 인용 된 코드는 JSON 아닙니다 . 코드는 JavaScript 개체 리터럴 표기법입니다. JSON 은 더 쉬운 구문 분석을 위해 설계된 하위 집합입니다.

코드는 오브젝트 (정의 data배열 (함유) items객체) (AN 각각 id, name, 및 type).

이를 위해 jQuery가 필요하거나 필요하지 않으며 JavaScript 만 있으면됩니다.

항목 추가 :

data.items.push(
    {id: "7", name: "Douglas Adams", type: "comedy"}
);

그것은 끝에 추가됩니다. 중간에 추가하려면 아래를 참조하십시오.

항목 제거 :

여러 가지 방법이 있습니다. splice방법은 가장 다양합니다.

data.items.splice(1, 3); // Removes three items starting with the 2nd,
                         // ("Witches of Eastwick", "X-Men", "Ordinary People")

splice 원래 배열을 수정하고 제거한 항목의 배열을 반환합니다.

중간에 추가 :

splice실제로 추가와 제거를 모두 수행합니다. splice메서드 의 서명 은 다음과 같습니다.

removed_items = arrayObject.splice(index, num_to_remove[, add1[, add2[, ...]]]);
  • index -변경을 시작할 인덱스
  • num_to_remove -해당 색인으로 시작하여이 많은 항목을 제거하십시오.
  • addN -... 다음 요소 삽입

따라서 다음과 같이 세 번째 위치에 항목을 추가 할 수 있습니다.

data.items.splice(2, 0,
    {id: "7", name: "Douglas Adams", type: "comedy"}
);

의미 : 인덱스 2에서 시작하여 0 개 항목을 제거한 후 다음 항목을 삽입합니다. 결과는 다음과 같습니다.

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "2", name: "Witches of Eastwick", type: "comedy"},
    {id: "7", name: "Douglas Adams", type: "comedy"},     // <== The new item
    {id: "3", name: "X-Men", type: "action"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]};

일부를 제거하고 한 번에 추가 할 수 있습니다.

data.items.splice(1, 3,
    {id: "7", name: "Douglas Adams", type: "comedy"},
    {id: "8", name: "Dick Francis", type: "mystery"}
);

... 즉, 인덱스 1에서 시작하여 세 항목을 제거한 다음이 두 항목을 추가합니다. 결과 :

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "7", name: "Douglas Adams", type: "comedy"},
    {id: "8", name: "Dick Francis", type: "mystery"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]};

Splice is good, everyone explain splice so I didn't explain it. You can also use delete keyword in JavaScript, it's good. You can use $.grep also to manipulate this using jQuery.

The jQuery Way :

data.items = jQuery.grep(
                data.items, 
                function (item,index) { 
                  return item.id !=  "1"; 
                });

DELETE Way:

delete data.items[0]

For Adding PUSH is better the splice, because splice is heavy weighted function. Splice create a new array , if you have a huge size of array then it may be troublesome. delete is sometime useful, after delete if you look for the length of the array then there is no change in length there. So use it wisely.


If you are using jQuery you can use the extend function to add new items.

var olddata = {"fruit":{"apples":10,"pears":21}};

var newdata = {};
newdata['vegetables'] = {"carrots": 2, "potatoes" : 5};

$.extend(true, olddata, newdata);

This will generate:

{"fruit":{"apples":10,"pears":21}, "vegetables":{"carrots":2,"potatoes":5}};

That's not JSON at all, it's just Javascript objects. JSON is a text representation of data, that uses a subset of the Javascript syntax.

The reason that you can't find any information about manipulating JSON using jQuery is because jQuery has nothing that can do that, and it's generally not done at all. You manipulate the data in the form of Javascript objects, and then turn it into a JSON string if that is what you need. (jQuery does have methods for the conversion, though.)

What you have is simply an object that contains an array, so you can use all the knowledge that you already have. Just use data.items to access the array.

For example, to add another item to the array using dynamic values:

// The values to put in the item
var id = 7;
var name = "The usual suspects";
var type = "crime";
// Create the item using the values
var item = { id: id, name: name, type: type };
// Add the item to the array
data.items.push(item);

Well, it's just a javascript object, so you can manipulate data.items just like you would an ordinary array. If you do:

data.items.pop();

your items array will be 1 item shorter.


Adding an object in a json array

var arrList = [];
var arr = {};   
arr['worker_id'] = worker_id;
arr['worker_nm'] = worker_nm;
arrList.push(arr);

Removing an object from a json

It worker for me.

  arrList = $.grep(arrList, function (e) { 

        if(e.worker_id == worker_id) {
            return false;
        } else {
            return true;
        }
    });

It returns an array without that object.

Hope it helps.


Keep things simple :)

var my_form_obj = {};
my_form_obj.name = "Captain America";
my_form_obj.weapon = "Shield";

Hope this helps!


Try

data.items.pop();
data.items.push({id: "7", name: "Matrix", type: "adult"});

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "2", name: "Witches of Eastwick", type: "comedy"},
    {id: "3", name: "X-Men", type: "action"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]};

data.items.pop();
data.items.push({id: "7", name: "Matrix", type: "adult"});

console.log(data);

참고URL : https://stackoverflow.com/questions/4538269/adding-removing-items-from-a-javascript-object-with-jquery

반응형