如何从对象数组中提取对象(数组)? [英] How do I extract an object(array) from an array of objects?

查看:191
本文介绍了如何从对象数组中提取对象(数组)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数据集:

const art = {
    'fields': [
        {title:'Title 1'}, 
        {'text': [
            {spaces: '1'}, {link: 'This is a link'}, {mouse: 'Yes'}
        ]}, 
        {title: 'Title 2'}, 
        {title:'Title 3'},
        {'text': [
            {spaces: '2'}, {link: 'This is a different link'}, {mouse: 'No'}
        ]},
    ]};

我想从空格"属性中提取一个新对象(数组).除此之外,我需要用空白值标识那些没有空格"属性的标题"对象.

I would like to extract a new object(array) from the "spaces" property. In addition to that, I need to to identify those "title" objects that do not have a "spaces" property associated with them with a blank value.

我想以这样的方式结束:

I'd like to end up with something like this:

newArray = ['', '1', '', '', '2']

这可能吗?如果我的术语不是很好,请原谅我.新来的.

Is this possible? Forgive me if my terminology isn't great. New at this.

推荐答案

应该不会太难.试试 Javascript 的 map() 函数...

It shouldn't be too hard. Try Javascript's map() function...

const art = {
    'fields': [
        {title:'Title 1'}, 
        {'text': [
            {spaces: '1'}, {link: 'This is a link'}, {mouse: 'Yes'}
        ]}, 
        {title: 'Title 2'}, 
        {title:'Title 3'},
        {'text': [
            {spaces: '2'}, {link: 'This is a different link'}, {mouse: 'No'}
        ]},
    ]};

const spaces = art.fields.map(function(field) {
  if(field.text) {
    return field.text[0].spaces;
  }
  return '';
});

console.log("Spaces?");

console.log(spaces);

结果...

"Spaces?"
["", "1", "", "", "2"]

查看用于 JSBIN 的代码.Map 返回一个函数对数组的迭代结果.查看 Mozilla 开发者网络文档 就可以了.

See the code working on JSBIN. Map returns a function's result for an iteration over an array. Check out the Mozilla Developer Network Docs on it.

这篇关于如何从对象数组中提取对象(数组)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆