programing

자바 스크립트 : 객체 리터럴 값 반복

nasanasas 2021. 1. 9. 10:09
반응형

자바 스크립트 : 객체 리터럴 값 반복


상단에 기본 설정을 생성하는 표준 jQuery 플러그인이 설정되어 있습니다.

jQuery.fn.myPlugin = function(options) { 
    var defaults = {  
        starts: "0px,0px",
        speed: 250, ...
    };
    o = $.extend(defaults, options);
}

라는 또 다른 변수가 numberOfObjects있습니다.

기본 변수를 반복하려고합니다. 찾은 각 개체 numberOfObjects에 대해 변수 값의 값을 복제해야합니다. 그래서, 만약 numberOfObjects변수가 3의가 defaults.starts있어야한다 0px,0px > 0px,0px > 0px,0px. >는 값을 분할하는 데 사용됩니다.

이것이 내가 현재 가지고있는 것입니다. X기본값 내의 변수 이름을 나타냅니다. Y의 현재 값에 대한 변수를 나타냅니다 x. 나는 여기까지 왔고 다음에 무엇을해야할지 전혀 모른다.

for (x in defaults) {   // x is defaults.x
    defaults.x = defaults.x + " > y";
}

var obj = {
    'foo': 1,
    'bar': 2
};

for (var key in obj) {
    console.log(obj[key]);
}

또는 jQuery 사용 :

$.each(obj, function(key, value) {
    console.log(this, value, obj[key]);
});

이를 위해 jQuery에 의존 할 필요가 없습니다.

Object.keys(obj).forEach(function (key) {
  var value = obj[key];
   // do something with key or value
});

시작하기 전에 기본 개체를 설정해 보겠습니다.

const x = {
  x: 1,
  y: 2,
  z: 3
};

Object.keys (x)를 사용하여 객체 내의 모든 키 배열을 반환 할 수 있습니다.

Object.keys(x)
> ['x', 'y', 'z']

이제 배열을 매핑, 필터링, 축소 및 반복하고 객체 내에서 해당 값으로 작업을 수행 할 수 있습니다.

Object.keys(x).map(key => x[key] + 1)
> [2,3,4]

Object.keys(x).forEach(key => console.log(x[key]))
> [1,2,3]

여기서 가장 중요한 점은 특정 값에 액세스하기 위해 키를 사용해야한다는 것입니다. 작동하지만 약간 어색해 보입니다. ES2017은 .NET 파일 Object.values()내의 모든 값의 배열을 반환하는 멋진 바로 가기로 사용할 수 있습니다 Object.

Object.values(x)
> [1,2,3]

Object.values(x).map(value => value + 1)
> [2,3,4]

Object.values(x).forEach(value => console.log(value))
> [1,2,3]

MDN 에서 Object.values ​​()에 대해 자세히 읽을 수 있으며 , 아직 구현하지 않은 이전 브라우저 및 브라우저를 지원해야하는 경우 polyfill도 포함되어 있습니다.


Best practice is to validate if the object attribute that is being iterated over is from the object itself and not inherited from the prototype chain. You can check this using .hasOwnProperty(): (Of course if you do want to include inherited properties just remove the if statement).

Here is the general case:

for(var index in object) { 
   if (object.hasOwnProperty(index)) {
       var value = object[index];
       // do something with object value here.
   }
}

Here is the example case you mentioned where you want to create a duplicate object with the value of each key duplicated replicated according to the value of the var numberofobjects (i've added in two solutions whereby you either modify the existing object or create a new one):

// function to repeat value as a string inspired by disfated's answer here http://stackoverflow.com/questions/202605/repeat-string-javascript

function repeatValue(value, count) {
    value = String(value); // change to string to be able to add " > " as in question
    if (count < 1) return '';
    var result = '';
    while (count > 1) {
        if (count & 1) result +=  value + " > ";
        count >>= 1, value += " > " + value;
    }
    return result + value;
}

var numberofobjects = 3;
var newObject = {}; // for use if creating a duplicate object with the new values

for(var x in defaults) { 
   if (defaults.hasOwnProperty(x)) {
       //use this to replace existing values
       defaults[x] = repeatValue(defaults[x], numberofobjects);

       //or use this to create values in the new object
       newObject[x] = repeatValue(defaults[x], numberofobjects);
   }
}

To iterate over an object's values you can use a for...of loop with Object.values.

const myObj = {a: 1, b: 2}

for (let value of Object.values(myObj)) {
    console.log(`value=${value}`)
}

// output: 
// value=1
// value=2

If you want the key and value when iterating, you can use Object.entries.

const myObj = {a: 1, b: 2}

for (let [key, value] of Object.entries(myObj)) {
    console.log(`key=${key} value=${value}`)
}

// output: 
// key=a value=1
// key=b value=2

In your code:

for(x in defaults){
   defaults.x = defaults.x + " > y";
}

You need to say defaults[x] instead of defaults.x.

x is a variable holding a string that is the key into the defaults object, and the bracket (array-style) syntax lets you use that variable to get the property. With the dot notation defaults.x is looking for a property actually called "x", the equivalent of defaults["x"].


var yourVariable = {
  Bobe: 23,
  Pope: 33,
  Doop: 43,
  Dope: 53
};

for(var keyName in yourVariable){
 document.write(keyName, " : ",yourVariable[keyName]," ");
};

ReferenceURL : https://stackoverflow.com/questions/9354834/javascript-iterate-over-object-literal-values

반응형