如何根据数组对象将数组对象转换/过滤为新的json对象?

时间:2017-07-24 22:42:31

标签: javascript arrays json

我有一个像这样的对象数组:

[{id: 1, name: 'foo', sport: 'soccer'},
{id: 2, name: 'bar', sport: 'basketball'},
{id: 3, name: 'acme', sport: 'basketball'},
{id: 4, name: 'xyz', sport: 'baseball'}]

如何将这个对象数组转换为一个按运动值过滤的新javascript对象?像这样:

{
    soccer: [{id: 1, name: 'foo'}],
    basketball: [{id: 2, name: 'bar'},{id: 3, name: 'acme'}],
    baseball: [{id: 4, name: 'xyz'}]
}

2 个答案:

答案 0 :(得分:0)

试试这个:

from sqlalchemy import Column, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.types import Boolean, Integer, String


Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    active = Column(Boolean, nullable=False)


url = 'postgresql://postgres@localhost/test'
engine = create_engine(url, echo=True)
if not engine.dialect.has_table(engine.connect(), 'users'):
    Base.metadata.create_all(bind=engine)
    Session = sessionmaker(bind=engine)
    session = Session()
    session.add(User(name="remram", active=True))
    session.commit()

Session = sessionmaker(bind=engine)
session = Session()
session.connection(execution_options={'isolation_level': 'SERIALIZABLE'})  # Commenting this line will make this unsafe in a concurrent environment

user = session.query(User).filter(User.name == "remram").one()
if user.active:
    user.active = False
raw_input()  # So you can run this twice
session.commit()

答案 1 :(得分:0)

您可以使用Array.prototype.reduce() https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

这样的事情:

array.reduce(function (accumulator, currentValue) {
  var sport = currentValue.sport;
  delete currentValue.sport;
  accumulator[sport] = accumulator[sport] || [];
  accumulator[sport].push(currentValue)
  return accumulator;
}, {});