게하! 개하! (게임도 하고 개발도 하고)

[JavaScript] Manipulating Complex Objects 본문

Javascript

[JavaScript] Manipulating Complex Objects

Sorrel 2021. 10. 6. 16:27
var myMusic = [
    {
        "artist": "Billy",
        "title": "Piano Man",
        "release_year": 1973,
        "formats": [
            "CD",
            "8T",
            "LP"
        ],
        "gold": true
    },
    {
        "artist": "Beau",
        "title": "Cereal Man",
        "release_year": 2003,
        "formats": [
            "Youtube video"
        ],
        "gold": true
    }
]
//manipulating complex objects
var myStorage = {
    "car":{
        "inside":{
            "glove box": "maps",
            "passenger seat": "crumbs"
        },
        "outside":{
            "trunk": "jack"
        }
    }
};

var gloveBoxContents = myStorage.car.inside["glove box"];
//nested objects
var myPlants = [
    {
        type: "flowers",
        list: [
            "rose",
            "tulip",
            "dandelion"
        ]
    },
    {
        type: "trees",
        list:[
            "fir",
            "pine",
            "birch"
        ]
    }
];

var secondTree = myPlants[1].list[1]; //pine
//nested Arrays;
var collection = {
    "2548": {
        "album": "Slippery When Wet",
        "artist": "Bon Jovi",
        "tracks": [
            "Let It Rock",
            "You Give Love a Bad Name"
        ]
    },
    "2468": {
        "album": "1999",
        "artist": "Prince",
        "tracks": [
            "1999",
            "aaa"
        ]
    },
    "1245":{
        "artist": "Robert Palmer",
        "tracks": []
    },
    "5439":{
        "album": "ABBA Gold"
    }
};

var collectionCopy = JSON.parse(JSON.stringify(collection));
//stringfy : json Object --> string
//parse : string --> json Object

function updateRecord(id, prop, value){
    if(value === ""){
        delete collection[id][prop];
    }else if(prop === "tracks"){
        collection[id][prop] = collection[id][prop] || [];
        collection[id][prop].push(value);
    }else{
        collection[id][prop] = value;
    }

    return collection;
}
updateRecord(2468, "tracks","test");
console.log(updateRecord(5439, "artist", "ABBA"));


//실행결과
{
  '1245': { artist: 'Robert Palmer', tracks: [] },
  '2468': {
    album: '1999',
    artist: 'Prince',
    tracks: [ '1999', 'aaa', 'test' ]
  },
  '2548': {
    album: 'Slippery When Wet',
    artist: 'Bon Jovi',
    tracks: [ 'Let It Rock', 'You Give Love a Bad Name' ]
  },
  '5439': { album: 'ABBA Gold', artist: 'ABBA' }
}

'Javascript' 카테고리의 다른 글

[JavaScript] 자주 쓰이는 함수  (0) 2021.10.06
[JavaScript] 랜덤 숫자  (0) 2021.10.06
[JavaScript] Manipulating Complex Objects  (0) 2021.10.06
[JavaScript] 객체 생성 (Object)  (0) 2021.10.06
[JavaScript] boolean return, null return  (0) 2021.10.06
[JavaScript] switch  (0) 2021.10.06
0 Comments
댓글쓰기 폼