从特定JSON字段中提取数据,将其用作变量,并更新字段值?

时间:2018-06-14 11:07:20

标签: javascript arrays json node.js geolocation

我需要将原始值更改为lat / lang坐标(来自另一个geoJson文件)而不是国家/地区名称:

index = [
  {
    "Name": "Aish Merahrah",
    "Origin": "Egypt",
    "Description": "Made with fenugreek seeds and maize; dough allowed to 
ferment overnight, then flattened and baked."
  },
  {
    "Name": "Ajdov Kruh",
    "Origin": "Slovenia",
    "Description": "Made with buckwheat flour and potato."
  }
]

所以结果会是这样的:

  {
    "Name": "Ajdov Kruh",
    "Origin": "46.151241, 14.995463",
    "Description": "Made with buckwheat flour and potato."
  }

我不确定工作流程,我是否需要提取JSON值变量并以某种方式使用该变量来获取lat&朗数据?顺便说一下,我需要才能使用JS / JQuery和Node。

3 个答案:

答案 0 :(得分:1)

使用Array.forEach

<field string="Year" name="year" filter_domain="[('moves_ids.date', '&gt;=', str(self) + '-01-01'), ('moves_ids.date', '&lt;=', str(self) + '-12-31')]" />

答案 1 :(得分:0)

假设您的geoJson具有以下结构(国家/地区名称为键,lat / long为值):

geolocation = {"Slovenia": "46.151241, 14.995463", "Egypt": "1, 1"}

您可以使用Array.prototype.map来迭代index并使用Origin中的值替换每个对象的geolcoation

&#13;
&#13;
index = [
  {
    "Name": "Aish Merahrah",
    "Origin": "Egypt",
    "Description": "Made with fenugreek seeds and maize; dough allowed to ferment overnight, then flattened and baked."
  },
  {
    "Name": "Ajdov Kruh",
    "Origin": "Slovenia",
    "Description": "Made with buckwheat flour and potato."
  }
]
geolocation = {"Slovenia": "46.151241, 14.995463", "Egypt": "1, 1"};
result = index.map(function(obj) { obj['Origin'] = geolocation[obj['Origin']]; return obj }); 
console.log(result);
&#13;
&#13;
&#13;

您甚至可以使用forEach进行上述迭代,但仍会更改index,因为更改是在参考对象中完成的。

答案 2 :(得分:0)

只需迭代对象索引,然后使用您的值编辑值。

假设给定的JSON数据:

&#13;
&#13;
// Creates an Object
let index = [
  {
    "Name": "Aish Merahrah",
    "Origin": "Egypt",
    "Description": "Made with fenugreek seeds and maize; dough allowed to ferment overnight, then flattened and baked."
  },
  {
    "Name": "Ajdov Kruh",
    "Origin": "Slovenia",
    "Description": "Made with buckwheat flour and potato."
  }
]

console.log(`Original Origin 1: ${index[0].Origin}\nOriginal Origin 2: ${index[1].Origin}`);

// Iterate over indices
for(let i=0;i<index.length;i++) {
  // Edit the value
  index[i].Origin = "1234/1234"
}

/*
// Using forEach
index.forEach((elem) => {
  elem.Origin = "Your Value";
});
*/

console.log(`Edited Origin 1: ${index[0].Origin}\nEdited Origin 2: ${index[1].Origin}`);
&#13;
&#13;
&#13;