首页 \ 问答 \ 如何将此JavaScript数组对象附加到另一个JavaScript数组对象?(How to append this JavaScript array object to another JavaScript array object?)

如何将此JavaScript数组对象附加到另一个JavaScript数组对象?(How to append this JavaScript array object to another JavaScript array object?)

我有这个Javascript json数组对象;

var dataJson=[ [{v:1},{v:90}],[{"v":2},{"v":"33.7000"}] ];

我想将这个数组对象dataJson附加到另一个对象,使它看起来像这样;

var chartObject = {"cols": [
    {id: "t", label: "t_label", type: "number"},
    {id: "s", label: "s_label", type: "number"} 
], "rows": [
    {c: 
        [{v:1},{v:90}] //dataJson[0]
    },
    {c: 
        [{"v":2},{"v":"33.7000"}] ////dataJson[1]
    }
]};

如何使用for循环将dataJson元素插入chartObject ? 对不起,我对javascript很新,甚至无法生成一些启动代码。 非常感谢您的帮助。


I have this Javascript json array object;

var dataJson=[ [{v:1},{v:90}],[{"v":2},{"v":"33.7000"}] ];

I want to append this array object dataJson to another object such that it looks like this;

var chartObject = {"cols": [
    {id: "t", label: "t_label", type: "number"},
    {id: "s", label: "s_label", type: "number"} 
], "rows": [
    {c: 
        [{v:1},{v:90}] //dataJson[0]
    },
    {c: 
        [{"v":2},{"v":"33.7000"}] ////dataJson[1]
    }
]};

How do I use a for loop to insert dataJson elements into chartObject? I am sorry I am quite new to javascript and can't even produce some starting code. Thank you very much for any help.


原文:https://stackoverflow.com/questions/22864304
更新时间:2022-07-09 07:07

最满意答案

这个问题没有简短的答案,所以我会给大纲随意提出更多问题,以便在需要时获得更多详细信息:

要使用数据绑定,请确保集合中的项目实现INotifyPropertyChanged。 目前您正在使用字符串数组。 字符串不实现INotifyPropertyChanged。

还要确保该集合实现了INotifyCollectionChanged。 目前您使用的是二维数组。 数组不实现此接口。

解决方案是创建一个名为Tile的类,该类实现INotifyPropertyChanged并将该字符存储为字符串,并在X和Y属性中另外存储其在板上的位置:

public class Tile : INotifyPropertyChanged
{
    private string character;
    public string Character
    {
        get
        {
            return character;
        }
        set
        {
            if(character != value)
            {
                character = value;
                OnPropertyChanged("Character");
            }
        }
    }

    private int x; // repeat for y and Y
    public int X
    {
        get
        {
            return x;
        }
        set
        {
            if(x != value)
            {
                x = value;
                OnPropertyChanged("X");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        var p = PropertyChanged;
        if(p != null)
        {
            p(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

创建一个类Tiles,如下所示:

public class Tiles : ObservableCollection<Tile>
{
}

并用此集合替换二维数组。

将项控件绑定到集合的一种方法是,您需要将items控件的DataContext设置为集合的实例并指定属性ItemsSource =“{Binding}”

使用itemtemplate中的Character,X和Y属性显示文本并定位切片。

这样,当您在添加或移除切片时操作Tiles集合时,绑定将自动更新视图,并且当切片更改(位置或内容)时,也会更新板


There is no short answer to this question, so I'll give an outline feel free to ask more questions to get more details where needed:

To use databinding make sure the items in the collection implement INotifyPropertyChanged. Currently you are using an array of strings. String do not implement INotifyPropertyChanged.

Also make sure the collection implements INotifyCollectionChanged. Currently you are using an two dimensional array. An array does not implement this interface.

A solution would be to create a class named Tile that implements INotifyPropertyChanged and stores the character as a string and additionally stores its position on the board in an X and Y property:

public class Tile : INotifyPropertyChanged
{
    private string character;
    public string Character
    {
        get
        {
            return character;
        }
        set
        {
            if(character != value)
            {
                character = value;
                OnPropertyChanged("Character");
            }
        }
    }

    private int x; // repeat for y and Y
    public int X
    {
        get
        {
            return x;
        }
        set
        {
            if(x != value)
            {
                x = value;
                OnPropertyChanged("X");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        var p = PropertyChanged;
        if(p != null)
        {
            p(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Create a class Tiles like this:

public class Tiles : ObservableCollection<Tile>
{
}

and replace the two dimensional array with this collection.

One way of binding an items control to the collection requires you to set the DataContext of the items control to an instance of the collection and specifying the property ItemsSource="{Binding}"

Use the Character, X and Y properties in the itemtemplate to display the text and position the tile.

This way the bindings will automagically update the view when you manipulate the Tiles collection when adding or removing tiles and the board will also be updated when a tile changes (either position or content)

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)