如何获取对象中的动态值

时间:2020-06-09 11:21:52

标签: javascript

我有一个类似

的对象
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",
        }
    ], 

但是,我面临的问题是,父对象中可以有动态键来进行提问和回答。

3 个答案:

答案 0 :(得分:2)

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

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; }

答案 1 :(得分:1)

假设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);

答案 2 :(得分:0)

您可以首先获取entries个对象,然后过滤掉其他静态部分,之后可以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);