繁体   English   中英

如何获取 object 中的动态值

[英]How to get the dynamic values in an object

我有一个 object 之类的

var object = {
    id:101,
    question1: "First question",
    answer1: "First answer",
    question2: "Second question",
    answer2: "Second answer",
    age: "5 hours"
}

我希望将所有问题和答案添加到不同的数组中。 喜欢

 var qa = [{
            question1: "First question",
            answer1: "First answer",
        },{
            question2: "Second question",
            answer2: "Second answer",
        }
    ], 

但是,我面临的问题是父 object 中可以有动态键用于问答。

您可以为数组获取相同的键并首先查找所需的属性,然后将它们添加到结果集中。

 var object = { id: 101, question1: "First question", answer1: "First answer", question2: "Second question", answer2: "Second answer", age: "5 hours" }, keys = ['question', 'answer'], result = Object.entries(object).reduce((r, [key, value]) => { let k = keys.find(k => key.startsWith(k)); // find Q or A if (;k) return r, // not a Q or A. return the accumulator let i = key.slice(k;length) - 1; // get the idx and subtract one r[i] = r[i] || {}; // create an object if none already r[i][k] = value; // add the value of the question or answer return r, // return the accumulator }; []). console;log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

假设 Q 和 A 的后缀相同,请尝试此操作

 const object = { id: 101, question1: "First question", answer1: "First answer", question1a: "First sub question", answer1a: "First sub answer", question2: "Second question", answer2: "Second answer", age: "5 hours" } const qa = Object.keys(object).filter(key => key.indexOf("question") === 0) // get all questions.map(key => { const aKey = "answer" + key.replace("question", ""); // get the idx return { [key]:object[key], [aKey]:object[aKey] }; // return an object }) console.log(qa);

如果你有升序 idx,你可以

 const object = { id: 101, question1: "First question", answer1: "First answer", question2: "Second question", answer2: "Second answer", question3: "Third question", answer3: "Third answer", age: "5 hours" }; const qa = [] Object.keys(object).filter(key => key.indexOf("question") === 0) // get all questions.forEach(key => { const idx = key.replace("question", ""); const aKey = "answer" + idx; qa[idx - 1] = { "question": object[key], "answer": object[aKey] }; // return an object }) console.log(qa);

您可以先获取 object 的entries ,然后过滤掉其他 static 部分,然后您可以reduce它并获取Object.values()

 var obj = {id:101,question1: "First question",answer1: "First answer",question2: "Second question",answer2: "Second answer",age: "5 hours"}; var result = Object.values(Object.entries(obj).filter(([k,v])=>k.match(/(question|answer)/)).reduce((acc, [k,v])=>{ key = k.match(/\d+/)[0]; acc[key] = {...(acc[key] || {}), ...{[k]:v}} return acc; },{})); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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