如何用父对象或字段包装JSON对象?

时间:2019-04-28 05:11:47

标签: javascript jquery html reactjs

我需要将名为filter_by_address的JSON字符串格式转换为具有这样的final output

{
  "input": {
    "citybooks": [
      {
        "city": "Moss Beach",
      },
      {
        "city": "Half Moon Bay",
      }
    ]
  }
}

我目前做的是以下代码:

var filtered = '[{"author":"Ernest Hemingway","title":"Snow White","address":"Sydney","link":{"url":"https://www.loremipsum.com"},"booktype":{"type":"Science Fiction"}},{"author":"J.K. Rowling","title":"Harry Potter","address":"Sydney","link":{"url":"https://www.loremipsum.com"},"booktype":{"type":"Textbook"}}]';
var books_data_array = JSON.parse(filtered);
var new_objects = [];

//console.log(books_data_array);

for (var i = 0; i < books_data_array.length; i++) {
  //console.log(books_data_array[i]["author"]);

  var new_object = {
    "citybooks": [{
      "city": "address",
    }]
  }

  new_objects.push(new_object);

}

console.log(new_objects);

我的代码仍然缺少某些内容。我需要将citybooks字段返回的所有对象包装在"input"中。

2 个答案:

答案 0 :(得分:3)

您可以使用map遍历数组并构造所需的结构。

var filtered = '[{"author":"Ernest Hemingway","title":"Snow White","address":"Sydney","link":{"url":"https://www.loremipsum.com"},"booktype":{"type":"Science Fiction"}},{"author":"J.K. Rowling","title":"Harry Potter","address":"Sydney","link":{"url":"https://www.loremipsum.com"},"booktype":{"type":"Textbook"}}]';
var books_data_array = JSON.parse(filtered);

var new_objects = {
  input: {
    citybooks: books_data_array.map(o => ({city: o.address})),
  }
}

console.log(new_objects);

答案 1 :(得分:1)

您也可以尝试用reduce进行操作,但这取决于您。

  var filtered = '[{"author":"Ernest Hemingway","title":"Snow White","address":"Sydney","link":{"url":"https://www.loremipsum.com"},"booktype":{"type":"Science Fiction"}},{"author":"J.K. Rowling","title":"Harry Potter","address":"Sydney","link":{"url":"https://www.loremipsum.com"},"booktype":{"type":"Textbook"}}]';
  const books_data_array = JSON.parse(filtered);
  var new_objects = [];

const filtered = books_data_array.reduce((cur, acc) => {
    const currEl = cur['input'].cityBooks;
    const addr = acc.address;
    const res = [...currEl, addr];
    return {input: {cityBooks: res}}
}, {input: {cityBooks:[]}})

console.log(filtered);