JavaScriptを理解してオブジェクトに書き込もうとしています。JavaScriptオブジェクトを検索して値を変更する方法
{
"name":"",
"children":[
{
"name":"Level 1",
"children":[
{
"name":"Level 2",
"children":[
{
"name":"Level 3",
"children":[
{
"name":"Level 4",
"children":[
{
"name":"Speed",
"children":null,
"id":6
}
],
"id":5
}
],
"id":4
}
],
"id":3
}
],
"id":2
},
{
"name":"Level 1",
"children":[
{
"name":"Level 2",
"children":[
{
"name":"Level 3",
"children":[
{
"name":"Level 4",
"children":[
{
"name":"Cost",
"children":null,
"id":11
}
],
"id":10
}
],
"id":9
}
],
"id":8
}
],
"id":7
},
{
"name":"Level 1",
"children":[
{
"name":"Level 2",
"children":[
{
"name":"Level 3",
"children":[
{
"name":"Level 4",
"children":[
{
"name":"Manufacturability",
"children":null,
"id":16
}
],
"id":15
}
],
"id":14
}
],
"id":13
}
],
"id":12
}
],
"id":1
}
と私は与えられたid
値を検索し、そのname
値を変更する方法を理解しようとしている:私はここにオブジェクトを持っています。私の場合
d.id
と
d.name
を使用して値にアクセスできることを知っている(これは、ウィジェット表示の一部である。
name
値がそれを移入)
var jstring = this.model.get('value') ? this.model.get('value') : "{}";
// where 'value' = demo.json
var root = JSON.parse(jstring)
var g = this.g = svg.selectAll("g")
.data(partition.nodes(root))
.enter().append("g");
var path = this.path = g.append("path")
.attr("d", arc)
.style("fill", function(d) {
d.active = d.active ? true : false
return d.active || d.center ? color[1] : color[0];
})
.on("dblclick",dblclick);
var text = this.text = g.append("text")
.attr("transform", function(d) { return "rotate(" + computeTextRotation(d) + ")"; })
.attr("x", function(d) { return y(d.y); })
.attr("dx", "6") // margin
.attr("dy", ".35em") // vertical-align
.text(function(d) { return d.name; });
例えば、Iウィジェット上の特定の領域をクリックすると、その値をd.name
に設定して入力ボックスに入力することができ、正しい値が得られます。
function dblclick(d)
{
var input = document.getElementById("name");
input.value = d.name;
$("#dialog").dialog(
{
buttons: {
Save: function() {
d.name = input.value;
var newString = JSON.stringify(root, function(key, val) {
if (Array.isArray(val)){
return val
}
if (val != null && typeof val == "object") {
val = _.pick(val, 'name', 'children', 'id');
if(d.id == val.id){
input.value = d.name;
console.log(d.name)
}
val.children = Array.isArray(val.children) ? val.children : [];
return val
}
return val
})
self.model.set('value', newString)
self.update()
console.log(newString)
私は同様の質問hereを見つけましたが、私は私のJSONを変更するための答えを適用する方法を理解していません。
また、私が試したことの真実があります:http://jsfiddle.net/CVvW4/237/。私は別の質問からの答えに従ったが、私の実装は間違っている。
正確に達成しようとしているのは何ですか?クリックイベントハンドラコードはどこですか?あなたはもっと具体的になりますか? – iulian
データツリーの特定の 'id'値を検索していますか?その場合は、検索関数を再帰的に呼び出す必要があります。 – C14L
@iulianそれはあまりにも多くのコードだと思ったので私はそれを残しましたが、私はそれを追加する編集します – c2bh2016