简体   繁体   中英

How to get value from index property in javascript?

Here is my code:

const array1 = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc', 
b: 'mno'}];
let obj = array1.reduce(function(result, item, index){
    result[index] = item
  return result;
}, {});

let dealId = 123;
let value = {};
let array2 = [];
for (var property in obj) {
   value[dealId] = array2.push(obj[property]);
}
console.log(value)

The output of this is Object { 123: 3 }

But I want and this is what I was expecting. Object { 123: [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc', b: 'mno'}] }

Why am I getting 3 instead of an array? How to get the array?

Why not build a new object with a single key and the given array as value?

For the object use a computed property name .

 const array = [{ a: 'abc', b: 'cd' }, { a: 'abc', b: 'xyz' }, { a: 'abc', b: 'mno' }], key = 123, object = { [key]: array }; console.log(object); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Array.prototype.push returns the new length of the array, not the array itself. Your loop assigns the values 1, 2 and 3 to the same value[dealId] .

Instead, you can move the assignment outside the loop:

for (var property in obj) {
   array2.push(obj[property]);
}
value[dealId] = array2;

Or you can simply use Object.values :

value[dealId] = Object.values(obj);

But note that this does not list inherited properties.

you need to add into aaray first then create the object

 const array1 = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc', b: 'mno'}]; let obj = array1.reduce(function(result, item, index){ result[index] = item return result; }, {}); let dealId = 123; let value = {}; let array2 = []; for (var property in obj) { array2.push(obj[property]); } value[dealId] = array2; console.log(value); 

 const array1 = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc', b: 'mno'}]; let obj = array1.reduce(function(result, item, index){ result[index] = item return result; }, {}); let dealId = 123; let value = {}; let array2 = []; for (var property in obj) { array2.push(obj[property]); } value[dealId] = array2; console.log(value) 

Assign your new obj property (id) the requested array:


  
 
  
  
    let arr = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc', 
    b: 'mno'}];
    let newObj = {};
    let id = 123;

    newObj[id] = arr;
    console.log(newObj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM