是否有可能在javascript中从对象数组中获取特定属性?

时间:2016-06-16 13:25:00

标签: javascript arrays object svg delimiter

我将以下对象传递给数组内的函数:

[ { id: 'WA1WA1WAbWA2WAaWAbWA9WA6-WAdWA2WAaWAd-4WAbWAcWA3-WAbWA3WA7WAa-WAcWAbWA8WA9WAcWA9WA9WA9WA3WA3WA3WA9',
obj: '<svg data="BusinessProductFigure" x="484.171875" y="123" id="WA1WA1WAbWA2WAaWAbWA9WA6-WAdWA2WAaWAd-4WAbWAcWA3-WAbWA3WA7WAa-    WAcWAbWA8WA9WAcWA9WA9WA9WA3WA3WA3WA9" 
xmlns="http://www.w3.org/2000/svg" version="1.1"><rect x="4" y="4" 
 width="60" height="14" fill="rgb(299,299,162)" stroke-linejoin="round" 
stroke="rgb(299,299,162)" stroke-width="1"/></svg>' } ]

是否可以在SVG标记内的单独变量中获取X和Y值?是否有任何条件或分隔符可以以某种方式使用?

2 个答案:

答案 0 :(得分:4)

&#13;
&#13;
var arr = [{
  id: 'JKIU',
  obj: '<svg data="BusinessProductFigure" x="484.171875" y="123" id="FRRR" xmlns="http://www.w3.org/2000/svg" version="1.1" > <rect x="4" y="4" width="60" height="14" fill="rgb(299,299,162)" stroke-linejoin="round" stroke="rgb(299,299,162)" stroke-width="1"/></svg>'
}];

var div = document.createElement('div');

div.innerHTML = arr[0].obj;

// var svg = div.querySelector('svg');
var svg = div.firstChild;

var x = svg.getAttribute('x');
var y = svg.getAttribute('y');

console.log(x, y);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

像这样使用DOMParser

var x = [ { id: 'WA...',
            obj: '<svg data="BusinessProductFigure" x="484.171875" y="123" id="WA..."  xmlns="http://www.w3.org/2000/svg" version="1.1"><rect x="4" y="4" width="60" height="14" fill="rgb(299,299,162)" stroke-linejoin="round" stroke="rgb(299,299,162)" stroke-width="1"/></svg>' } ]
           
var dom = new DOMParser().parseFromString(x[0].obj, 'image/svg+xml');

alert(dom.documentElement.getAttribute("x"));