简体   繁体   English

向JSON数组JavaScript添加元素

[英]adding an element to JSON Array JavaScript

I have the following array in my source code: 我的源代码中包含以下数组:

var employees = [
{
  "Question":"question 1",
  "Answer":"answer 1"
}, 
{
  "Question":"question 1",
  "Answer":"another answer 1"
},
{
  "Question":"question 2",
  "Answer":"answer 2"
}
];

I need to create a function that can group all the answers that are related to the same question and put the info in a JSON object 我需要创建一个函数,该函数可以将与同一问题相关的所有答案分组,然后将信息放入JSON对象

{
  "Question":"question 1",
  "Answer" : '[{"answer 1","another answer 1"}]'
},
 {
  "Question":"question 2",
  "Answer" : '[{"answer2"}]'
}

This line has many problems 这条线有很多问题

'[{"answer 1","another answer 1"}]'

First, since it's inside quotes, it's a string, not an object. 首先,因为它在引号内,所以它是字符串,而不是对象。 Second, you have an invalid object inside of an array. 其次,您在数组内有一个无效的对象。

If I understood you correctly, you're looking for something along the lines of 如果我对您的理解正确,那么您正在寻找一些类似的东西

employee[x].answers = ['answer1','answer2'];

assuming that, like everyone is saying, you don't really mean what you wrote, but what we all understood, my advice for this case is using underscore, it has the perfect requirements for this case, your code would be: 假设就像每个人都在说的那样,您并不是真正的意思,但是我们大家都知道,对于这种情况,我的建议是使用下划线,它对这种情况有完美的要求,您的代码将是:

var result = _.chain(employees)
  .groupBy('Question')
  .map(function(value, key) {
    return {
      Question: key,
      Answer: _.pluck(value, 'Answer')
    }
  })
  .value();

You can try this. 你可以试试看 call this function and pass the employees array to this and it will return your modified array 调用此函数并将employees数组传递给此函数,它将返回修改后的数组

function customJSON(employees){
  var newEmp = [],tmp = 0;
  for(var i=0; i<employees.length; i++){
    if(employees[i]){
        if(newEmp.indexOf(employees[i].Question)>-1){
            employees[newEmp.indexOf(employees[i].Question)].Answer.push(employees[i].Answer);
            employees.splice(i,1);
            --i;
        }else{
            newEmp.push(employees[i].Question);
            tmp = employees[i].Answer;
            employees[i].Answer = [tmp];
        }
    }
  }
  return employees;
}

 var employees = [ { "Question":"question 1", "Answer":"answer 1" }, { "Question":"question 1", "Answer":"another answer 1" }, { "Question":"question 2", "Answer":"answer 2" }]; var employeesNewDataFormat = []; for(var i=0; i<employees.length; i++){ var hasEntry = false; var index = -1; for(var j=0; j<employeesNewDataFormat.length; j++) { if(employeesNewDataFormat[j].Question === employees[i].Question) { hasEntry = true; index = j; break; } } if(hasEntry) { employeesNewDataFormat[index].Answer.push(employees[i].Answer); } else { employeesNewDataFormat.push({"Question":employees[i].Question, "Answer":[employees[i].Answer]}); } } console.log(JSON.stringify(employeesNewDataFormat)); 

As said in comments, you wrote your answers as strings not as an array of strings. 如评论中所述,您将答案写为字符串而不是字符串数组。

What you may want to acheive is this : 您可能想要达到的目标是:

var employees = [
  {
    "question":"question 1",
    "answers": ["answer 1"]
  }, 
  {
    "question":"question 2",
    "answers": ["answer 2", "some other answer", "... etc"]
  }
];

// add answers to question 1
employees[0].answers.push('a new anwser 1');

// add anwers to question 2
employees[1].answers.push('a new answer 2');

// ... and so on

that's how i see it if you want a clean way to add answers and have your answers related to your questions directly 如果您想要一种干净的方法来添加答案并直接与您的问题相关的答案,这就是我的看法

Now the function for this would be : 现在,此功能为:

 var employees = [ { "Question":"question 1", "Answer":"answer 1" }, { "Question":"question 1", "Answer":"another answer 1" }, { "Question":"question 2", "Answer":"answer 2" } ]; function groupAnswersToQuestions(employees){ var questions = [], result = []; // set all questions with same string to the same key for(var k in employees){ // set the question to an array if not set yet var q = employees[k].Question; if( ! questions[q]) questions[q] = []; // add the answer to the array questions[q].push(employees[k].Answer); } // re render a new array with the wanted structure for(var k2 in questions){ result.push({ question: k2, answers: questions[k2] }); } return result; } alert( JSON.stringify( groupAnswersToQuestions(employees), null, 2) ); 

You can use a map to keep track of the questions and add answers to the array attached to it: 您可以使用地图来跟踪问题,并为其附加的数组添加答案:

 var employees = [{ "Question":"question 1", "Answer":"answer 1" }, { "Question":"question 1", "Answer":"another answer 1" }, { "Question":"question 2", "Answer":"answer 2" }]; var questions = {}; for (var i = 0; i < employees.length; i++) { if (questions[employees[i].Question] === undefined) { questions[employees[i].Question] = []; } questions[employees[i].Question].push(employees[i].Answer) } alert(JSON.stringify(questions, null, 2)) 

This is a bit crude and verbose but it does what I think you are asking for: 这有点粗略和冗长,但确实可以满足您的要求:

var questions = {};
for (var i = employees.length - 1; i >= 0; i--) {
    var Question = '';
    for (var property in employees[i]) {
        // console.log(property);
        var val = employees[i][property];

        if (property == "Question") {
            Question = val;
            if (typeof questions[Question] == 'undefined') {
                questions[Question] = [];
            };

        }

        if(property == 'Answer') {
            questions[Question].push(val);
        }
    };
};
var new_employees = [];
for (var Question in questions) {
    var obj = {
        "Question": Question,
        "Answer": questions[Question]
    }
    new_employees.push(obj);
};
console.log(new_employees);

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

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