簡體   English   中英

在JavaScript中將對象值分配為數組

[英]Assign object value as array in javascript

如何在對象值中將值分配給數組? 它可能有多個輸入進來,並期望將輸入追加到數組中。

碼:

var ob = {};
$.each( input, function( key, value ) {
    var v = [];
    ob[key] = v.push(value);
      console.log( v );     
      console.log( "obj: " + ob );                          
      console.log( key + ": " + value );
    });

輸入:

First input- {A: "34",B: "2"}
Second input- {A: "21",B: "11"}

預期:

ob = {A: ["34","21"] ,B: ["2","11"]}

創建一個函數和一個對象變量。 檢查密鑰是否存在於該對象中。 如果不存在,則創建密鑰並推送值

 let input1 = { A: "34", B: "2" } let input2 = { A: "21", B: "11" } // a object which will hold the key and value let finalObj = {}; // create a function which will be called o add key an value property to object function createObj(obj) { // iterate the object for (let keys in obj) { // check if final object has the relevent key if (finalObj.hasOwnProperty(keys)) { // if it has that key then push the value according to the key finalObj[keys].push(obj[keys]) } else { finalObj[keys] = [obj[keys]] } } } createObj(input1) createObj(input2) console.log(finalObj) 

希望這可以幫助,

var ob = {};

$.each(input, function(key, value) {
    if (!ob[key]) {
        ob[key] = [];  // Creates a new Array for the key, if no array is there
    }
    ob[key].push(value);  // Pushes the value to the array of the particular key
});

問題是v清空,因為這條線的每個迭代,:

var v = [];

嘗試這樣做:

$.each(input, (key, val) => {
    if (ob[key]) {
        ob[key].push(val);
    } else {
        ob[key] = [val];
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM