如何从响应数组数据设置数据对象

时间:2018-11-08 10:37:55

标签: javascript arrays object

我有这样的响应数据

{
  "data": {
    "title": "dashboard",
    "description": "just test dashboard",
    "photos": [
      {
        "file_name": "12345454.jpg",
        "photo_name": "indonesia"
      },
      {
        "file_name": "567686.jpg",
        "photo_name": "jakarta"
      }]
  }
}

然后,我需要更改带有数组file_name且没有photos变量的数据的响应。

预期:file_name [0]将是数组的file_name索引的符号

像这样

{
  "data": {
    "title": "dashboard",
    "description": "just test dashboard",
    "file_name[0]": "12345454.jpg",
    "file_name[1]": "567686.jpg"
  }
}

我尝试过照片地图,但是没有用

this.data = this.data.photos.map((item, idx) => {
    let data = {
      file_name: item.file_name
    }
    return data
  })
  this.data.photos.map((item, idx) => {
    this.$set(this.data, 'file_name', item.file_name)
  })

4 个答案:

答案 0 :(得分:3)

尝试关注

let data = {"title": "dashboard","description": "just test dashboard","photos":[{"file_name": "12345454.jpg","photo_name": "indonesia"},{"file_name": "567686.jpg","photo_name": "jakarta"}]};

data.photos.forEach((v,i) => data[`file_name[${i}]`] = v.file_name);
delete data.photos;
console.log(data);

答案 1 :(得分:0)

我提议一种创建新对象的方法。

@Nikhil Aggarwal soluce变异现有对象

都很好,选择毒药:)

const old = {
  data: {
    title: 'dashboard',
    description: 'just test dashboard',
    photos: [
      {
        file_name: '12345454.jpg',
        photo_name: 'indonesia',
      },
      {
        file_name: '567686.jpg',
        photo_name: 'jakarta',
      }],
  },
};

const formatted = {
  // We use reduce to create the data object
  data: Object.keys(old.data).reduce((tmp, x) => {
    // If we are not dealing with photos key, just add the old data to the new object
    if (x !== 'photos') {
      tmp[x] = old.data[x];
      
      return tmp;
    }
    
    // for each photo, add a new key
    old.data.photos.forEach((y, yi) => {
      tmp[`file_name[${yi}]`] = y.file_name;
    });
    
    return tmp;
  }, {}),
};

console.log(formatted);

答案 2 :(得分:0)

如果我理解正确,您实际上希望print(y_data) >>>>[-5.34112443e+21 -2.50395581e+28 -6.75169134e+28] 是一个数组。如果是这样,并且您很乐意在适当位置更改对象,请尝试:

file_name

答案 3 :(得分:0)

看看这个例子。通过使用它,您可以重组或创建新的json。

<span id="text"></span><br/>
<span id="photosdata"></span>

这是逻辑

var obj = JSON.parse('{   "data": {     "title": "dashboard",     "description": "just test dashboard",     "photos": [       {         "file_name": "12345454.jpg",         "photo_name": "indonesia"       },       {         "file_name": "567686.jpg",         "photo_name": "jakarta"       }]   } }');

document.getElementById("text").innerHTML = obj.data.title+"<br/>";

var photos = obj.data.photos;

photos.forEach(function(item){
 document.getElementById("text").innerHTML += item.file_name +"<br/>";
});

https://jsfiddle.net/qufnwmd4/1/