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

Extract data from specific JSON field, use it as variable, and update the field value?

我需要将原点值更改为 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 值变量并以某种方式使用该变量来获取经纬度数据?顺便说一句,我 需要 仅使用 JS/JQuery 和 Node.

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

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

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

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

您甚至可以使用 forEach 在上面进行迭代,它仍然会更改 index,因为更改是在引用对象中完成的。

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

假设给定的 JSON 数据:


// 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}`);

使用Array.forEach

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."}];
let lat = {"Slovenia": "46.151241, 14.995463", "Egypt": "26.820553, 30.802498"};
index.forEach(o => o.Origin = lat[o.Origin] ?  lat[o.Origin] :  o.Origin); 
console.log(index);