javascript - 将某些数据从一个对象抓取到另一个对象

标签 javascript javascript-objects

我的目标是从数据库中获取某些值到 curated_database,但是我基本上坚持将多个项目添加到一个对象中。

var curated_database = {};

var database = {
    0: [{name: 'Micheal'}, 
        {age: 45},
        {education: 'BA'},  
        {income: 245000},  
        {occupation: 'director'}],
    1: [{name: 'John'}, 
        {age: 23},
        {education: 'BA'},  
        {income: 60000},  
        {occupation: 'manager'}],
    2: [{name: 'Judith'}, 
        {age: 45},
        {education: 'PhD'},  
        {income: 140000},  
        {occupation: 'professor'}],
    3: [{name: 'Gill'}, 
        {age: 28},
        {education: 'MS'},  
        {income: 98000},  
        {occupation: 'scientist'}],
    4: [{name: 'Dave'}, 
        {age: 17},
        {education: 'HS'},  
        {income: 30000},  
        {occupation: 'retail associate'}]
};

目标是从较大的物体中抓取相似的某些信息


curated_database = { 
0 : ['Micheal',245000,'director'],
1: ['John',245000,'manager'],
2: ['Judith',140000,'professor'],
3: ['Gill',98000,'scientist'],
4: ['Dave',30000,'retail associate']
};

我的尝试

for(data in database){
    desired_contents = [0,3,4]
    for(contents in desired_contents){
    console.log(database[data][desired_contents[contents]]);
    }
    var k = database[data][0];
    if (!currated_database[k.key]) {
        currated_database[k.key] = [];
    }
        currated_database[k.key].push(k.val);
}

最佳答案

你可以这样实现:

var curated_database = {};

var database = {
    0: [{name: 'Micheal'},
        {age: 45},
        {education: 'BA'},
        {income: 245000},
        {occupation: 'director'}],
    1: [{name: 'John'},
        {age: 23},
        {education: 'BA'},
        {income: 60000},
        {occupation: 'manager'}],
    2: [{name: 'Judith'},
        {age: 45},
        {education: 'PhD'},
        {income: 140000},
        {occupation: 'professor'}],
    3: [{name: 'Gill'},
        {age: 28},
        {education: 'MS'},
        {income: 98000},
        {occupation: 'scientist'}],
    4: [{name: 'Dave'},
        {age: 17},
        {education: 'HS'},
        {income: 30000},
        {occupation: 'retail associate'}]
};



var indexToExtract = new Set([0,3,4]);

    var wantedLst = Object.values(database)
    .map(lst => lst.filter((ob, idx) => indexToExtract.has(idx)))
    .map((lst, idx) => curated_database[idx] = lst.map(ob => Object.values(ob)[0]))
    
    console.log(curated_database);

关于javascript - 将某些数据从一个对象抓取到另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70633937/

相关文章:

javascript - 基于动态参数过滤数组

javascript - 从jquery中的对象数组中获取值

javascript - Eloquent JavaScript,第 2 版,练习 5.3 历史预期生命周期

javascript - 重定向到 url,如果 Jwplayer 加载媒体时出错

javascript - JQuery 动画导航

javascript - 重力形式求列表列的总和

javascript - NodeJs 以丑陋的二进制格式接收 UDP 数字

javascript - 使用 Javascript 将字符串与用户输入进行比较

javascript - 将对象内的对象作为参数传递给函数

javascript - 波斯语/阿拉伯语文本在从对象填充的下拉列表中未正确显示