簡體   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