选择JSON对象并添加新属性

时间:2017-11-06 05:21:50

标签: javascript json

我对javascript很新,并使用以下json。我的挑战是我想:

1. call an attribute
2. add a new attribute
3. add a prefix to the Url attribute

{
  "currency": [
    {},
    {
      "Name": "Product 1",
      "Url": "/currencies/product1/",
      "Symbol": "PT1",
      "Price": "$767.7",
    },
    {
      "Name": "Product 1",
      "Url": "/currencies/product1/",
      "Symbol": "PT1",
      "Price": "$767.7",
    }
  ]
}

我尝试通过url访问data.Url,但只是取消分配。

添加属性时,我的JSON应如下所示:

...
    {
      "Name": "Product 1",
      "Url": "/currencies/product1/",
      "Symbol": "PT1",
      "Price": "$767.7",
      "Market": "Europe"
    },
...

有关如何访问该属性并添加新属性的任何建议吗?

感谢您的回复!

2 个答案:

答案 0 :(得分:3)

这样的事情会做,希望有所帮助



var data = {
  "currency": [
    {},
    {
      "Name": "Product 1",
      "Url": "/currencies/product1/",
      "Symbol": "PT1",
      "Price": "$767.7",
    },
    {
      "Name": "Product 1",
      "Url": "/currencies/product1/",
      "Symbol": "PT1",
      "Price": "$767.7",
    }
  ]
}

var urls = [];

data.currency.forEach(function(cur) {
    if (cur.Url) urls.push(cur.Url);
    cur.Market = "Europe";
});

console.log(urls);
console.log(data);




答案 1 :(得分:1)

您无法获得价值,因为您需要先将JSON分配给变量。

让我们分析您的JSON。然后你会明白为什么你的方法不起作用。

在这个解释中,我们将它分为几个层次。

等级1

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="rightBtn" type="button" value="Left">

<div class="mycontainer">

  <div class="innerLiner">
    <span class="box">
      This is box1     
    </span>
    <span class="box">
      This is box2   
    </span>
    <span class="box box2">
      This is box3    
    </span>
  </div>

</div>
<input class="leftBtn" type="button" value="Right">

在此级别中,您可以通过此语法

获取“currency”的值
var data = {
    "currency": [...]
}

等级2

data.currency

事实证明,var data = { "currency": [ {}, {...}, {...} ] } 是一个数组。因此,要访问数组内部的值,您需要使用数组语法。例如,如果您想获得data.currency的第二项,则执行

data.currency

等级3

data.currency[1]

现在,var data = { "currency": [ {}, { "Name": "Product 1", "Url": "/currencies/product1/", "Symbol": "PT1", "Price": "$767.7", }, { "Name": "Product 1", "Url": "/currencies/product1/", "Symbol": "PT1", "Price": "$767.7", } ] }; 是一个对象。因此,您可以继续使用对象方法来获取值。例如

data.currency[1]

如果您想为其添加新属性(即“市场”),您只需编写

即可
data.currency[1].Url

注意

  1. data.currency[1].Market = "..." 处有一个空对象。如果你想循环使用它,请小心,因为如果你试图获取不存在的对象数据,它可能会抛出错误。
  2. 总结

    data.currency[0]

    我使用的方法是使用for循环。

    有关其他方法,请参阅AngYC's answer